我定义了一个
single file component
我想在该组件上使用props选项.
<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { data () { return { // note: changing this line won't causes changes // with hot-reload because the reloaded component // preserves its current state and we are modifying // its initial state. msg: 'Hello World!' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1 { color: #42b983; } </style>
解决方法
经过很长时间的实验,我发现了一个实用的解决方案:
项目文件结构:
src/ assets/ components/ Home.vue App.vue main.js package.json config.js index.html
现在,我们要访问子组件Home.vue中的根组件 – 应用程序的vm字段,并使用vue-route.
main.js:
import Vue from 'vue' import VueRouter from 'vue-router' import App from './App' Vue.use(VueRouter); let router = new VueRouter(); router.map({ '/': { name: 'home',component: require('./components/Home') } }); router.start(App,'body');
App.vue:
<template> <p>The current path: {{ $route.path }}.</p> <p>Outer-Value: {{ outer_var }}</p> <hr/> <!-- The below line is very very important --> <router-view :outer_var.sync="outer_var"></router-view> </template> <script> import Home from './compnents/Home.vue' export default { replace: false,components: { Home },data: function() { return { outer_var: 'Outer Var Init Value.' } } } </script>
Home.vue
<template> <div> <p><input v-model="outer_var" /></p> <p>Inner-Value: {{ outer_var }}</p> </div> </template> <script> export default { // relating to the attribute define in outer <router-view> tag. props: ['outer_var'],data: function () { return { }; } } </script>
结论
请注意,内部参数在组件标签的属性(< router-view> Tag,在这种情况下)绑定属性,而不是直接在父组件上.
因此,我们必须手动将传递的道具字段绑定到组件标签上的属性.见:http://vuejs.org/guide/components.html#Passing-Data-with-Props
另外,注意我在该属性上使用了.sync,因为默认情况下绑定是单向下拉的:http://vuejs.org/guide/components.html#Prop-Binding-Types
你可以看到,通过嵌套组件共享状态有点困惑.为了做一个更好的做法,我们可以使用Vuex.