我正在定义一个 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
现在,我们要访问根组件 -- App
子组件内的 vm 字段 Home.vue
, 与 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>
结论
请注意,内部 prop 将属性绑定(bind)到组件标签的属性上(在本例中为 <router-view>
标签。),不是直接在父组件上。
因此,我们必须手动将传递的 props 字段绑定(bind)为组件标签上的属性。请参阅:http://vuejs.org/guide/components.html#Passing-Data-with-Props
另外,请注意我使用了 .sync
在该属性上,因为默认情况下绑定(bind)是单向向下:http://vuejs.org/guide/components.html#Prop-Binding-Types
可以看到,通过嵌套组件来共享状态有点乱。为了更好地练习,我们可以使用 Vuex .
关于javascript - Vue.js:如何在单个文件组件中指定 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674891/