将 JavaScript 变量传递给 Vue

3

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

我有这个生成菜单并将所有值推入数组menu的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个回答

2
任何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元素上(它可以在您的组件内部)。以上只是一个基本实现,以演示原理。”

感谢您的精彩解释,向您致敬。 - Steve

0
使用props:
<service-menu-component :data=YOUR_ARRAY></service-menu-component>

在组件中:

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

1
jQuery 函数和组件都在 blade 模板中,我不能像这样将数据传递给组件。 - Steve

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>

1
jQuery函数和组件都在blade模板中,我无法像那样将数据传递给组件。 - Steve
我不确定。我没有使用过laravel/blade的经验。 - Shivam Kumar

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;
    },

它像魔法一样运行良好。


0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接