简体   繁体   English

如何在 vue.js 中动态添加新的数据元素

[英]how to add new data elements dynamically in vue.js

I'm using vue.js in a sort of an odd single page app, where I have areas that I dynamically load content into, and they interact with the others areas - ie none of the content is there at the start - I have a custom vue component that sort of works like v-html - but causes the new html to be parsed by vue.我在一种奇怪的单页应用程序中使用 vue.js,在那里我有一些区域可以动态加载内容,并且它们与其他区域交互 - 即一开始没有任何内容 - 我有一个类似于 v-html 的自定义 vue 组件 - 但会导致新的 html 被 vue 解析。

And it all works great.这一切都很好。

Except for data bindings.除了数据绑定。 Any existing data bindings work perfectly - so if I have this:任何现有的数据绑定都可以完美运行 - 所以如果我有这个:


   var data = 
   {
       some_string : "hello",
       some_object :  {
            whatever : 10
       }
   }

Any of the things I read later can quite happily interact with all of those variables - show them, bind both ways etc etc.我后来读到的任何东西都可以很愉快地与所有这些变量交互 - 显示它们,双向绑定等等。

HOWEVER - I can't add anything new.但是 - 我无法添加任何新内容。 If I try - it just doesn't get watched.如果我尝试 - 它只是不会被监视。

Which means that in my wonderful, completely dynamic, code is data environment - I have to go back and change the main template every time I want to create a new variable :(这意味着在我美妙的、完全动态的、代码是数据环境中 - 每次我想创建一个新变量时,我都必须返回并更改主模板:(

Is there any command to be able to tell vue about a new variable, after it's been created?在创建新变量之后,是否有任何命令能够告诉 vue 一个新变量? I'm imagining something like:我在想象这样的事情:

vue.watch_new_variable( data.new_object );

or even甚至

vue.refresh_watches_of_data();

found it - was really simple - I have an object on data called global - and then I can just dynamically add to it with Vue.set - eg找到了 - 真的很简单 - 我有一个名为 global 的数据对象 - 然后我可以使用 Vue.set 动态添加到它 - 例如

Vue.set( data.global, "my_new_value", 10 );

and from then on, I can bind to, address, change global.my_new_value and it all seems to work perfectly.从那时起,我可以绑定到、寻址、更改 global.my_new_value 并且这一切似乎都完美无缺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM