Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

javascript - 是否可以在某些Vue数据元素更改时触发功能?(Is it possible to trigger a function upon some Vue data elements change?)

I need to watch for a batch of data elements and when they will be changed, store them into localStorage.(我需要注意一批数据元素,当它们将被更改时,将它们存储到localStorage中。)

Is there any convenient way to do this?(有什么方便的方法吗?)   ask by Иван translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use watchers for this.(您可以为此使用观察程序。)

<script> const SomeComponent = { name: 'SomeComponent', data() { someData: null, }, watch: { 'someData': { handler(newValue, oldValue) { // sets off when `someData` changes this.someMethod(); }, immediate: true, // if you also want to execute the handler above on creation of the component }, }, methods: { someMethod() { // do something with this.someData } } </script> Sadly, you have to add a watcher for every data element that you want to watch, even if you want to execute the same function.(遗憾的是,即使您要执行相同的功能,也必须为要监视的每个数据元素添加一个监视程序。) If you want to avoid this you can create an object in your data, put your data inside this object and watch this object.(如果要避免这种情况,可以在数据中创建一个对象,将数据放入该对象中并观察该对象。) You then need to pass deep: true at the watcher (like we did with immediate in the example above).(然后,您需要通过deep: true的观察者(就像我们做了与immediate在上面的例子)。) This will watch for all changes on the object and trigger the method accordingly.(这将监视对象上的所有更改并相应地触发方法。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...