我正在定义一个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>发布于 2016-04-17 22:41:21
经过长时间的实验,我找到了一个实用的解决方案:
项目文件结构:
src/
assets/
components/
Home.vue
App.vue
main.js
package.json
config.js
index.html现在,我们想要访问根组件--子组件Home.vue中的App的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>标记)的属性上的属性,而不是直接在父组件上的。
因此,我们的必须手动将传递的props字段绑定为组件标记上的一个属性。请参阅:http://vuejs.org/guide/components.html#Passing-Data-with-Props
另外,请注意,我在该属性上使用了.sync,因为默认情况下绑定是one-way-down:http://vuejs.org/guide/components.html#Prop-Binding-Types
您可以看到,通过嵌套组件共享状态有点令人困惑。为了进行更好的实践,我们可以使用Vuex。
发布于 2016-10-04 16:21:37
你可以这样做:
app.js
<template>
<div class="hello">
<h1>{{ parentMsg }}</h1>
<h1>{{ childMsg }}</h1>
</div>
</template>
<script>
export default {
props: ['parentMessage'],
data () {
return {
childMessage: 'Child message'
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>main.js
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
data() {
return {
message: 'Parent message'
}
},
render(h) {
return h(App, { props: { parentMessage: this.message } })
}
});发布于 2018-01-17 16:20:56
从几个月前开始,Vue就有了自己的styleguide,用于参考和类似的东西。道具是参考资料之一,实际上是一个必不可少的参考资料。
坏的
props: ['status']好的
props: {
status: String
}甚至更好
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}您可以在此here上找到更多信息
https://stackoverflow.com/questions/36674891
复制相似问题