我正在定义一个 文件组件
我想在该组件上使用 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>
原文由 Alfred Huang 发布,翻译遵循 CC BY-SA 4.0 许可协议
经过长时间的实验,我找到了一个实用的解决方案:
项目文件结构:
现在,我们要访问根组件
App
子组件Home.vue
内的 vm 字段,开启vue-route
。主.js:
应用程序.vue:
主页.vue
结论
请注意,内部道具将属性绑定在组件标签的属性上(在这种情况下为
<router-view>
标签。),而 不是 直接在父组件上。因此,我们 必须 手动将传递的 props 字段绑定为组件标签上的属性。见:http: //vuejs.org/guide/components.html#Passing-Data-with-Props
另外,请注意我在该属性上使用了
.sync
,因为默认情况下绑定是 单向的:http: //vuejs.org/guide/components.html#Prop-Binding-Types可以看到,通过嵌套组件共享状态有点混乱。为了更好地实践,我们可以使用 Vuex 。