![](/img/trans.png)
[英]How can i access child component method in parent component using ref in Vue3?
[英]Vue3 how to access an element in a child component from the parent (options)
如何从父组件影响子组件中的元素? 我下面的代码是我试图实现的简化版本,评论显示了各种失败的尝试。
家长:
import InputText from "./InputText.js";
export default {
components: { InputText },
template: `
{{ things }}<br><br>
<input-text v-for="thing in things" :key="thing.id" :thing="thing" />
<br><br>
<button @click="focusBox()">TEST</button>
`,
data() {
return {
things: [{
"id": 1,
"name": ""
}, {
"id": 2,
"name": ""
}, {
"id": 3,
"name": ""
}]
}
},
methods: {
focusBox() {
// this.$refs.thing.id[2].focus();
this.$nextTick(() => this.$refs.thing_2.focus());
}
}
}
孩子:
export default {
template: `
<input type="text" v-model="thing.name" :ref="'thing_' + thing.id">
<!-- <input type="text" v-model="thing.name" ref="thing.id"> -->
<br>
`,
props: {
thing: Object
}
}
提前谢谢了。
您可以观察属性变化:
const app = Vue.createApp({ data() { return { things: [{"id": 1, "name": ""}, {"id": 2, "name": ""}, {"id": 3, "name": ""}], focused: null } }, }) app.component('inputText', { template: ` <input type="text" v-model="thing.name":ref="'thing'"> <br> `, props: { thing: Object, focused: Boolean }, watch: { focused(val, oldVal) { if(this.thing.id === val) this.$refs.thing.focus() }, } }) app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> {{ things }}<br><br> <input-text v-for="thing in things":key="thing.id":thing="thing":focused="focused"></input-text> <br> <p>insert thing id</p> <input type="number" v-model="focused" /> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.