Javascript 如何从vue.js中的子文件更改父文件的数据值?
我在vue.js中有一个全新的应用程序。我想使用在子组件中选中的复选框更改app.vue的数据值我将如何执行此操作我在两个文件中使用的代码是:- 组件文件:-Javascript 如何从vue.js中的子文件更改父文件的数据值?,javascript,vue.js,Javascript,Vue.js,我在vue.js中有一个全新的应用程序。我想使用在子组件中选中的复选框更改app.vue的数据值我将如何执行此操作我在两个文件中使用的代码是:- 组件文件:- <template> <div> <h3>Edit the user</h3> <p>Local: {{ $route.query.local }}</p> <p>Number is:- {{ $route.query.q
<template>
<div>
<h3>Edit the user</h3>
<p>Local: {{ $route.query.local }}</p>
<p>Number is:- {{ $route.query.q }}</p>
<label><input type="checkbox" @click="change()">customizer</label>
</div>
</template>
<script>
export default{
props:["changeParentStatus"],
methods:{
change() {
this.active = !this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
</script>
可以将函数作为属性传递给子组件
<app-header :changeParentStatus="changeStatus"></app-header>
母公司
回拨
从“/components/Header.vue”导入AppHeader;
导出默认值{
数据(){
返回{
主动:正确
}
},
方法:{
更改状态(活动){
this.active=active
}
},
组成部分:{
appHeader:appHeader
}
}
现在从子更改函数调用“changeParentStatus”
<script>
export default{
props:["changeParentStatus"],
methods:{
change() {
this.active = !this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
</script>
导出默认值{
道具:[“changeParentStatus”],
方法:{
更改(){
this.active=!this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
看起来您希望将复选框值从子项传递给父项。为此,在父组件上定义事件并从子组件发出该事件
在父句柄事件中,如下所示:
<router-view @changeParentStatus="changeStatus"></router-view>
更多信息:使用您的代码时出现错误。changeParentStatus不是一个函数您能告诉我如何解决这个问题吗?因此,如果您在路由器视图中使用它,您需要像这样传递它,然后在子道具的道具中定义它:[“changeParentStatus”]。如果它不能解决你的问题,请分享你的代码。但它会给我错误。你能编辑你的答案并再次发布它,它不会显示错误吗@USER6761351在使用代码时,还有一个错误,
属性或方法“checked”未在实例上定义,而是在渲染期间引用。确保此属性在数据选项或基于类的组件中是被动的
您能帮助解决此问题吗?是否在子组件的数据中定义了此属性?如果不是,则定义为数据:{checked:false}-对于单个复选框,它是布尔值。我发现您不需要在子项中绑定/维护选中状态,您可以在单击复选框时直接向父项发出调用,更新代码。现在,您不需要在child中使用数据/方法。
<script>
import AppHeader from "./components/Header.vue";
export default {
data(){
return{
active: true
}
},
methods:{
changeStatus(active){
this.active=active
}
},
components:{
appHeader: AppHeader
}
}
</script>
<script>
export default{
props:["changeParentStatus"],
methods:{
change() {
this.active = !this.active
console.log(this.active)
this.changeParentStatus(this.active);
}
}
}
</script>
<router-view @changeParentStatus="changeStatus"></router-view>
<label>
<input type="checkbox"
@click="$emit('changeParentStatus', $event.target.checked)">
customizer</label>