我有一个组件,我将其用作嵌套组件(更多级别的组件),并由 vue-router 安装的组件使用。有时我从父级传递数据,或将其设置在组件内。
我的组件:
module.exports = {
props: {
post: {
default: Object
}
}
mounted() {
if( ! this.post.id) {
this.$http.get('posts/' + this.$route.params.post).then((r) => {
// This works fine
this.post.id = r.data.id
// This gives warn, to avoid mutate property directly,
// because the parent will overwrite it.
// But here, there is no parent (with post data)!
// If I set post as data(), also gives a warn cause the props setting
this.post = r.data
})
}
},
// other parts...
}
嵌套版本:
在嵌套方式中,我将属性传递给组件,如下所示:
<post :post="post"></post>
路由器版本
只是简单地将组件传递给路由器
{name : 'post/:post', component: Post}
如何设置属性没有警告? (在我以两种不同方式使用组件的情况下)我有很多帖子的属性,所以一个一个地添加它不是那么干净。我也不想设置 <router-view :post="post">
组件。
最佳答案
不鼓励从子组件中直接更改父数据。
为了触发变化,子组件可以发出一个事件,然后使用 v-on 指令调用父方法,然后更新数据,这个更新的数据向下流到子组件,它自动更新。
阅读有关单向数据流的更多信息: https://vuejs.org/guide/components.html#One-Way-Data-Flow
// Post component
const post = Vue.component('post', {
template: '#post-template',
props: {
post: {
default: Object
}
},
mounted() {
// from child component just emit the change
// and let parent handle the change
this.$emit('load-post');
}
});
// Root Vue Instance
new Vue({
el: '#app',
data() {
return {
post: {
description: "waiting for post to load..."
}
}
},
methods: {
getPost() {
// perform your ajax request here
// and update the variable from parent.
self = this;
setTimeout(function() {
self.post = {
description: "this is some random description"
}
}, 2000)
}
},
components: {
post: post
}
})
<script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
<body>
<div id="app">
<post :post="post" v-on:load-post="getPost"></post>
</div>
</body>
<template id="post-template">
<div>
Post: {{ post.description }}
</div>
</template>
关于vue.js - Vue 如何在具有父级和自身的组件上设置属性? [警告],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421945/