表格(父)组件:
angular.module('tAngularApp')
.controller('MainCtrl', ["$scope", "$rootScope", function ($scope, $rootScope) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.rooms = [
{id:1, name: "Room #1"},
{id:2, name: "Room #2"},
{id:3, name: "Room #3"},
{id:4, name: "Room #4"}
];
$scope.selectedRooms = [];
$scope.Add_Remove_Room = function (roomID) {
var index = $scope.selectedRooms.indexOf(roomID);
if(index === -1){
// If is not selected the room -> add it
$scope.selectedRooms.push(roomID);
} else {
// If is selected the room -> remove it
$scope.selectedRooms.splice(index, 1);
}
}
}]);
和c-tool-bar组件(子)在c-form的插槽内(如果存在)
export default {
template: `
<form name="form" class="c form" v-on:change="onChange">
<slot></slot>
</form>`,
methods: {
onChange:function(){
console.log("something changed");
}
}
};
我想要实现的是,当export default {
template: `
<div class="c tool bar m006">
<div v-if="changed">
{{ changedHint }}
</div>
<!-- some other irrelevant stuff -->
</div>`,
props: {
changed: {
type: Boolean,
default: false,
},
changedHint: String
}
};
的onChange被触发时,该功能
检查儿童c-tool-bar是否存在&amp;&amp;它有一个声明的changeHint文本(从后端)它应该改变c-form
的道具&#34;更改&#34;为true并且c-bar-tool自行更新,以便c-tool-bar
实际显示changedHint。我阅读了vue.js文档,但我不知道从哪里开始,以及正确的方法是什么。
答案 0 :(得分:2)
您可以使用以下两个组件:
<parent-component></parent-component>
您将在:changed
中传递data()
中父组件中定义的变量。请注意:
,我们正在使用dynamic props,因此一旦在父级中更改了prop值,它也会更新子级。
要更改提示的显示,请将作为prop传递的变量的值更改为子组件:
export default {
template: `
<form name="form" class="c form" v-on:change="onChange">
<child-component :changed="shouldDisplayHint"></child-component>
</form>`,
data() {
return {
shouldDisplayHint: false,
};
},
methods: {
onChange:function(){
this.shouldDisplayHint = true; // change the value accordingly
console.log("something changed");
}
}
};
答案 1 :(得分:1)
一种简单的方法是使用$refs
。
当您在父组件中创建子组件时,您应该具有以下内容:<c-tool-bar ref="child">
,然后您可以在父组件代码中使用它:
methods: {
onChange:function(){
this.$refs.child.(do whatever you want)
}
}
希望它有所帮助,但如有任何疑问:https://vuejs.org/v2/guide/components.html#Child-Component-Refs