gpt4 book ai didi

javascript - 更新组件

转载 作者:行者123 更新时间:2023-11-30 21:17:27 24 4
gpt4 key购买 nike

我误解了如何更新组件。所以,这是 HTML :

<div id="app">

<form v-on:submit="submitForm">
<input type="text" id="txtSearch">
<input type="submit" value="go">
</form>

<br><br>

<user></user>

</div>

还有 JS:

let userComponent = {
template: 'your name is : {{name}}<br>You are {{age}}'
};

let vueApp = new Vue({
el: '#app',

components: {'user': userComponent},

methods: {
submitForm: function(e) {
e.preventDefault();
let val = document.getElementById('txtSearch').value;
alert('submitted : ' + val);
// normally i do a search here : let result = mySearch(val);
// but let's do the job with this :
let result = {name: 'John', age: 27};
// so now, how to modify the <user> with this data result ?
}
}
});

所以,我的目标是创建一个模板,当然还有更新他的数据。这个怎么做 ?我创建了一个用于测试的 jsfiddle:https://jsfiddle.net/4w0kh30t/1/感谢您的帮助。

最佳答案

首先,您的 vue 实例需要一个数据,以使您的数据具有反应性。因此,向您的 vueApp 添加数据,如下所示:

let vueApp = new Vue({
el: '#app',
data: {
person: {
name: '',
age: 0,
}
}
components: {'user': userComponent},
methods: {
submitForm: function(e) {
e.preventDefault();
let val = document.getElementById('txtSearch').value;
alert('submitted : ' + val);
// normally i do a search here : let result = mySearch(val);
// but let's do the job with this :
let result = {name: 'John', age: 27};
// so now, how to modify the <user> with this data result ?
}
}
});

现在要进行更改,您需要使用 this.person = something,which womething 将是您在提交事件方法中的结果,如下所示:

submitForm: function(e) {
e.preventDefault();
let val = document.getElementById('txtSearch').value;
alert('submitted : ' + val);
// normally i do a search here : let result = mySearch(val);
// but let's do the job with this :
let result = {name: 'John', age: 27};
this.person = result
}
}

现在,要让您的组件对更改使用react,它必须通过属性或 Prop 接收数据。将组件更改为此:

let userComponent = {
props: ['user'],
template: 'your name is : {{name}}<br>You are {{age}}'
};

最后需要在vue实例的模板中将person传递给组件:

<user :user="person"></user>

结果在这里:

https://jsfiddle.net/jhs7ffch/1/

关于javascript - 更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com