[英]In Vue.js.How to pass value from main to compent or template
例子:
var index = new Vue({
el:'#main',
components: { Index },
template: '<Index/>',
data:{
divCount:'',
boxs:[],
}
})
我添加了能力
Vue.component(
method:
function(){
//i wish use divCount in here,and how?
}
)
或者
我在 main.js var author = 'john' 中定義了一個全局值;
import Vue from 'vue'
import Index from './Index'
var author = "john";
我希望在 Index.vue 頁面中使用這個值
<script>
module.exports ={
data(){
//
},
mounted() {
console.log(author);//it's wrong,how i can use?
}
}
</script>
非常感謝~
處理此問題的推薦方法是使用 JS 對象來存儲您的值。 這允許您更新它們並將更改反映在您的應用程序中。 有關更多信息,請參閱此文檔頁面,其中還包含有關大型應用程序的更好做法的更多信息。
這是一個如何實現的示例:
// store.js
const store = {
author: "john",
}
export default store
// Index.vue
<template>
<div>{{ store.author }}</div>
</template>
<script>
import store from './store'
export default {
data() {
return { store }
}
}
</script>
對於簡單的應用程序,您可以只使用總線而不是 vue : Vue-Js 文檔中的非父子通信部分的更多信息: https ://v2.vuejs.org/v2/guide/components.html
有時兩個組件可能需要相互通信,但它們不是彼此的父/子。 在簡單的場景中,你可以使用一個空的 Vue 實例作為中央事件總線:
var bus = new Vue()
// in component A's method
bus.$emit('id-selected', 1)
// in component B's created hook
bus.$on('id-selected', function (id) {
// ...
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.