将 Javascript 变量传递给 Vue

时间:2021-01-16 12:41:26

标签: javascript laravel vue.js

如何将 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 作为后端。

5 个答案:

答案 0 :(得分:1)

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

在 Vue 中,这种行为称为 反应性。如果这就是你想要的,你可以使用 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 元素上(它可以在您的 <service-menu-component> 组件内)。以上只是一个基本的实现,用来演示原理。

答案 1 :(得分:0)

使用道具:

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

在组件中:

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

答案 2 :(得分:0)

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

你的 Parent.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>

答案 3 :(得分:0)

在尝试不同的事情后使它工作并且看起来很简单的原因是将 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;
    },

它就像一个魅力。

答案 4 :(得分:0)

@Ş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 }} 这取决于传入的数据,我的朋友。