是否可以有多个 Vuejs 实例? [英] Are multiple Vuejs instances possible?

查看:40
本文介绍了是否可以有多个 Vuejs 实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个真实应用的简化示例:

<身体><script src="https://unpkg.com/vue"></script><div id="应用程序"><div id="子应用程序"><p>{{ 信息}}</p>

<p>{{消息}}</p>

<脚本>新的 Vue({el: '#app',数据: {消息:你好 Vue.js!"}})新的 Vue({el: '#subapp',数据: {消息:'¡Hola Vue.js!'}})</html>

我希望看到两条不同的消息,但我收到了两次相同的消息.如果我在子应用程序"中将 message 更改为 other_message,Vuejs 会抱怨它找不到 other_message.

有没有办法将它们嵌入"在一起?除了取消嵌入 html 部分或合并控制器之外,有没有办法获得预期的结果?或者,对于我要完成的工作,是否有更好的术语?(英语有时很难)

解决方案

就像@ka_lin 所说的,你应该为此使用组件.它们是实现此目的的完美工具.

否则几乎不可能做到,特别是对于您提供的示例.Vuejs 无法识别 {{ message }} 属于哪个实例.

实现类似"功能的最接近的方法是将 vue 实例的范围分配给两个元素,如下所示:

new Vue({el: '#app1',数据 () {返回 {消息:'你好'}},})新的 Vue({el: '#app2',数据 () {返回 {消息:'你好'}}})

<script src="https://unpkg.com/vue@2.5.9/dist/vue.js"><;/脚本><div id="app1">{{ 信息 }}

<div id="app2">{{ 信息 }}

Consider this simplified example of a real-world app:

<html>
  <body>
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <div id="subapp">
        <p>
          {{ message}}
        </p>
      </div>
      <p>{{ message }}</p>
    </div>

    <script>
      new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue.js!'
        }
      })

      new Vue({
        el: '#subapp',
        data: {
          message: '¡Hola Vue.js!'
        }
      })

    </script>
  </body>
</html>

I'd expect to see two different messages, but i get the same message twice. If i change message to other_message in the 'subapp', Vuejs complains that it can not find other_message.

Is there a way to "embed" them together? Short of un-embedding the html part or merging the controllers, is there a way of getting the expected result? Alternatively, is there a better term for what i'm trying to accomplish? (english is hard sometimes)

解决方案

Like @ka_lin has said, you should use components for this. They are the perfect tools for this.

Otherwise it is almost impossible to do, specially with the example you have presented. There is no way Vuejs can recognize to which instance {{ message }} belongs to.

The closest you can achive a 'similar' feature is to distribute the scope of your vue instance to two elements as:

new Vue({
 el: '#app1',
 data () {
   return {
     message: 'Hello'
   }
 },
})

new Vue({
 el: '#app2',
 data () {
   return {
     message: 'Helloa'
   }
 }
})

<script src="https://unpkg.com/vue@2.5.9/dist/vue.js"></script>

<div id="app1">
  {{ message }}
</div>

<div id="app2">
  {{ message }}
</div>

这篇关于是否可以有多个 Vuejs 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆