Vue3, complex watch implementation, solution For the second time

CSDN Q & A 2022-05-15 04:51:37 阅读数:184

vue3vuecomplexwatchimplementation

Purpose , Listen in the array , An uncertain location ( Custom location ) The elements of , Change . Elements other than customization change No matter
Please test and modify with the following , Thank you very much
in addition , If the user does not define the location to listen , That means you can't listen , It seems that this function is not easy to realize

<template><div> <p> Array arr:{
{
arr}}</p> <p> monitor arr Array , Where the element changes :<input type="text" v-model="position"></p> <p>arr Array ,{
{
position}} The element value of the position is changed to :<input type="text" v-model="arr[position]"></p> <p> Monitoring Report :{
{
info}}</p></div></template><script>import { reactive, watch, toRefs } from 'vue'export default { name:'Debug', setup(props){ const data =reactive({ arr:['a','b','c','d','e'], position:'', // Which element in the array  info:'', // Prompt information  }) // Error below ,  // Next, if you listen data.arr Can work normally , But the purpose is to monitor arr An uncertain element in an array , Not to listen to all elements  watch(data.arr[data.position],(newValue)=>{ console.log(' There is a change ') data.info = ' Change to new value :'+ newValue //.....// }) // It's impossible to change it like this  // watch(()=>{data.arr[data.position]},(newValue)=>{
 // console.log(' There is a change ') // data.info = ' Change to new value :'+ newValue // }) return { ...toRefs(data), } }}</script>



Take the answer :
<template> <div> <p> Array arr:{
{
arr}}</p> <p> monitor arr Array , Where the element changes :<input type="text" v-model="position" ></p> <p>arr Array ,{
{
position}} The element value of the position is changed to :<input type="text" v-model="arr[position]" ></p> <p> Monitoring Report :{
{
info}}</p> </div></template><script>import { reactive, watch, toRefs } from "vue";export default { name: "Debug", setup(props) { const data = reactive({ arr: ["a", "b", "c", "d", "e"], position: "", // Which element in the array  info: "", // Prompt information  }); // Error below , // Next, if you listen data.arr Can work normally , But the purpose is to monitor arr An uncertain element in an array , Not to listen to all elements  // watch(data.arr[data.position], (newValue) => {
 // console.log(" There is a change "); // data.info = " Change to new value :" + newValue; // //.....// // }); // It's impossible to change it like this  watch( () => data.arr[data.position], (newValue) => { console.log(" There is a change "); data.info = " Change to new value :" + newValue; } ); return { ...toRefs(data), }; },};</script>

版权声明:本文为[CSDN Q & A]所创,转载请带上原文链接,感谢。 https://primo.wiki/2022/131/202205041430340340.html