1

我試圖擺弄Rails 5.1的新webpacker gem以及VueJS,但無法獲取我的erb視圖將數據傳遞給VueJS組件...將數據從Rails視圖傳遞到Webpacker中的VueJS組件

比方說,我有一個用戶展示視圖

# view/users/show.html.erb 
<%= javascript_pack_tag "user-card" %> 
<%= content_tag :div, 
    id: "user-card", 
    data: { 
    username: @user.name 
    } do %> 
<% end %> 

而且我的javascript:

// app/javascript/packs/user-card.js 
require("user-card") 

// app/javascript/user-card/index.js 
import Vue from 'vue/dist/vue.esm' 
import UserCard from './components/UserCard' 

document.addEventListener('DOMContentLoaded',() => { 
    let element = document.getElementById("user-card") 
    let username = element.dataset.username 
    console.log(username); // => "pecpec" 

    const app = new Vue({ 
    el: element, 
    template: '<UserCard/>', 
    components: { UserCard }, 
    data() { 
     return { username } 
    } 
    }) 


// app/javascript/user-card/components/UserCard.vue 
<template> 
    <div> 
    <h3>Hello {{ username }}</h3> 
    </div> 
</template> 

<script> 
export default { 
    props: ['username'], 
    data() { 
    return { 
     username: "" 
    } 
    } 
} 
</script> 

我已經花了幾個小時了這一點,現在,但是沒有我的嘗試已經證明成功的。我試着將數據傳遞到組件的道具: props: ['username'],與

Vue.component(UserCard, { 
    props: ['username'] 
    // or 
    data() { 
    return { username: username } 
    } 
}) 

安裝該組件...但沒有工作,要麼

更新: 我在失蹤props: ['username']該組件並相應地更新了上面的代碼,儘管這似乎沒有改變。仍然沒有運氣!

回答

6

It 作品!這是我的解決方案...不知道這是否是規範的方法,但它仍然有效。現在看起來非常明顯......希望這會幫助其他人。以下是全部更新代碼:

# view/users/show.html.erb 
<%= javascript_pack_tag "user-card" %> 
<%= content_tag :div, 
    nil, 
    id: "user-card", 
    data: { username: @user.name } 
%> 
// app/javascript/packs/user-card.js 
require("user-card") 

// app/javascript/user-card/index.js 
import Vue from 'vue/dist/vue.esm' 
import UserCard from './components/UserCard' 

document.addEventListener('DOMContentLoaded',() => { 
    let element = document.getElementById("user-card") 
    let username = element.dataset.username 

    const app = new Vue({ 
    el: element, 
    data: { username: username }, 
    template: '<UserCard :username="username"/>', 
    components: { UserCard } 
    }) 
}) 

// app/javascript/user-card/components/UserCard.vue 
<template> 
    <div> 
    <h3>Hello {{ username }}</h3> 
    </div> 
</template> 

<script> 
export default { 
    props: ['username'] 
} 
</script>