【问题标题】:Pass Javascript Variable to Vue将 Javascript 变量传递给 Vue
【发布时间】:2021-04-21 06:56:44
【问题描述】:

如何将 Javascript 变量传递给 Vue 组件?

我有这个 jQuery 函数,它生成菜单并将所有值推送到数组菜单中:

var menu = [];

$(document).ready(function(){
    $('.service-desc-wrap h2,.cta-button').each(function(){
        if($(this).hasClass('cta-button')) {
            if($(this).attr('title') && $(this).attr('href')) {
                var linkTitle = $(this).attr('title');
                var href = $(this).attr('href');
                data = [
                    title = linkTitle, 
                    href = href,
                ]
                menu.push(data);
                $('#menu, #menuMobile').append('<a class="menuText" href="'+href+'">'+linkTitle+'</a>')
            };
        } else {
            var tag = $.slugify($(this).text());
            $(this).attr('id',tag);
            var linkTitle = $(this).text();
            if($(this).attr('title')) {
                var linkTitle = $(this).attr('title');
            };
                data = [
                    title = linkTitle, 
                    href = tag,
                ]
                menu.push(data);
            $('#menu, #menuMobile').append('<a class="menuText" href="#'+tag+'">'+linkTitle+'</a>')
        }
    }); 
}); 

我想将数组传递给一个名为

的 Vue 组件
<service-menu-component></service-menu-component>

jQuery 函数和组件在一个 Blade.php 文件中,我使用 Laravel 作为后端。

【问题讨论】:

  • 它在刀片模板中的事实完全无关紧要。告诉我们这就像告诉店主硬币是从你夹克的左边口袋里放出来的,而不是从右边口袋里放出来的。它来自哪里并不重要。重要的是它的价值以及使用它的时间(运行代码时)。因此,在您的示例中,唯一重要的是代码何时由生成的 html 页面执行,其中 jQuery 和 Vue 都应该工作和通信。

标签: javascript laravel vue.js


【解决方案1】:

任何 Vue 组件都可以访问全局范围(也称为 window 对象),$ 在其中执行。你不必为此做任何特别的事情。简而言之,如果在创建 Vue 组件时已在全局范围内声明了一个变量 - Vue 可以访问它。但是 Vue 不会对该变量的内容执行的后续更改做出反应。无论如何,不​​是开箱即用的。

在 Vue 中,这种行为称为 reactivity。如果这是你想要的,你可以使用Vue.observable():

  • 声明一个 const,持有一个响应式引用(在本例中为 store.menu - 将其命名为对您有意义的任何名称)
  • 在您的 Vue 组件中使用 computed,返回响应式引用
  • 在任何时候(在创建 Vue 实例之前或之后)从任何地方(包括外部 Vue 组件/实例)修改引用,Vue 实例将获得更改

概念证明:

Vue.config.productionTip = false;
Vue.config.devtools = false;
// you don't need the above config, it just suppresses some warnings on SO

// declare store, with whatever contents you want:
const store = Vue.observable({menu: []}); 

// optionally push something to menu:
// works before Vue instance was created
store.menu.push({foo: 'bar'});

$(function() {
  // optionally push something to menu 
  // also works after Vue instance was created - i.e: 3s after $(document).ready()
  setTimeout(function() {
    store.menu.push({boo: 'far'});
  }, 3000)
})

new Vue({
  el: '#app',
  computed: {
    menu() {
      // this injects the store's menu (the reactive property) in your component
      return store.menu
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <pre v-text="menu"></pre>
</div>

computed 不必位于根 Vue 元素上(它可以在您的 &lt;service-menu-component&gt; 组件内)。以上只是一个基本的实现,演示原理。

【讨论】:

    【解决方案2】:

    使用道具:

    <service-menu-component :data=YOUR_ARRAY></service-menu-component>
    

    在组件中:

    props: ['data'] // the data being passed.
    

    【讨论】:

    • jQuery 函数和组件在刀片模板中,我无法像那样将数据传递给组件。
    【解决方案3】:

    是的,您可能需要将此 jQuery sn-p 文件导入您的父组件,然后将其传递给您的 service-menu-component。 代码如下所示:

    你的父母.vue

    <template>
        <service-menu-component :data=menu></service-menu-component>
    </template>
    <script src="<pathToYourJqueryFile>"></script>
    

    然后在你的service-menu-component:

    <template>
       <div>
          {{ menu }}
      </div>
    </template>
    <script>
    export default {
      name: 'service-menu-component',
      props: {
          menu: {
              type: Array
          }
      }
    }
    </script>
    

    【讨论】:

    • jQuery 函数和组件在刀片模板中,我无法像那样将数据传递给组件。
    • 那我不确定。我没有使用 laravel/blade 的经验。
    【解决方案4】:

    在尝试不同的事情之后让它工作并且看起来很简单的原因是在组件挂载的钩子中移动 jQuery 函数,如下所示:

        mounted() {
                var menu = [];
    
                $(document).ready(function(){
                    $('.service-desc-wrap h2,.cta-button').each(function(){
                        if($(this).hasClass('cta-button')) {
                            if($(this).attr('title') && $(this).attr('href')) {
                                var linkTitle = $(this).attr('title');
                                var href = $(this).attr('href');
                                data = {
                                    'title': linkTitle, 
                                    'href': href,
                                }
                                menu.push(data);
                                $('#menu, #menuMobile').append('<a class="menuText ml-2" href="'+href+'">'+linkTitle+'</a>')
                            };
                        } else {
                            var tag = $.slugify($(this).text());
                            $(this).attr('id',tag);
                            var linkTitle = $(this).text();
                            if($(this).attr('title')) {
                                var linkTitle = $(this).attr('title');
                            };
                                var data = {
                                    'title': linkTitle, 
                                    'href': tag,
                                }
                                menu.push(data);
                            $('#menu, #menuMobile').append('<a class="menuText ml-2" href="#'+tag+'">'+linkTitle+'</a>')
                        }
                    });
                    console.log(menu);
                   
                }); 
    
                 this.menu = menu;
        },
    

    它就像一个魅力。

    【讨论】:

      【解决方案5】:

      @Şivam Kuvar verdiği örnekteki gibi :data='menu' yazan yeri :data="json_encode($controllerdata)" ile değiştir ve verilerini kullanmaya hazırsın。 veri yapına göre @{{ data.data[0].title }} olabilir örneğin veya @{{ data.title }} bu gelen veriye bağlı dostum。

      就像@Şivam Kuvar 的示例一样,将 :data='menu' 替换为 :data="json_encode($controllerdata)" 即可使用您的数据。根据数据结构,例如可以是@{{ data.data[0].title }} 或@{{ data.title }},这取决于传入的数据,我的朋友。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-11
        • 2018-09-23
        • 2012-01-28
        • 2012-10-24
        • 2019-03-24
        • 2021-04-16
        相关资源
        最近更新 更多