是否可以有多个 Vuejs 实例?

编程入门 行业动态 更新时间:2024-10-10 23:26:25
本文介绍了是否可以有多个 Vuejs 实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

<身体><script src="https://unpkg/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/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/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/vue@2.5.9/dist/vue.js"></script>

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

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

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

更多推荐

[db:关键词]

本文发布于:2023-04-27 02:47:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1146364.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   实例   Vuejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!