最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

laravel - Pass Javascript Variable to Vue - Stack Overflow

programmeradmin1浏览0评论

How can i pass a Javascript Variable to a Vue Component?

I have this jQuery function which generates the menu and pushes all the Values inside the array menu:

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>')
        }
    }); 
}); 

I want to pass the array to a Vue Component called

<service-menu-ponent></service-menu-ponent>

The jQuery Function and the Component are inside a blade.php file, i'm using Laravel as a backend.

How can i pass a Javascript Variable to a Vue Component?

I have this jQuery function which generates the menu and pushes all the Values inside the array menu:

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>')
        }
    }); 
}); 

I want to pass the array to a Vue Component called

<service-menu-ponent></service-menu-ponent>

The jQuery Function and the Component are inside a blade.php file, i'm using Laravel as a backend.

Share Improve this question edited Jan 16, 2021 at 14:00 Steve asked Jan 16, 2021 at 12:41 SteveSteve 6452 gold badges10 silver badges22 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 3

Any Vue ponent has access to the global scope (a.k.a window object), in which $ performs. You don't have to do anything special about it. In simpler words, if a variable has been declared in global scope at the time your Vue ponent is created - Vue can access it. But Vue won't react to later mutations performed on the contents of that variable. Not out of the box, anyway.

In Vue, that behavior is called reactivity. If that's what you want, you could use Vue.observable():

  • declare a const, holding a reactive reference (store.menu in this example - name it to whatever makes sense to you)
  • use a puted in your Vue ponent, returning the reactive reference
  • at any point, (before or after Vue instance's creation) modify the reference from anywhere (including outside Vue ponent/instance) and the Vue instance will get the change

Proof of concept:

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',
  puted: {
    menu() {
      // this injects the store's menu (the reactive property) in your ponent
      return store.menu
    }
  }
})
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <pre v-text="menu"></pre>
</div>

The puted doesn't have to be on the root Vue element (it can be inside your <service-menu-ponent> ponent). The above is just a basic implementation, to demo the principle.

Use props:

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

In the ponent:

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

Yes, It's possible you need to import this jQuery snippet file to your parent ponent, and then pass it down to your service-menu-ponent. Here's how the code should look like:

Your Parent.vue

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

And then in your service-menu-ponent:

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

What made it work and seemed simple after trying different things is moving the jQuery function inside the ponent mounted hook like this:

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

It worked like a charm.

@Ş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.

Just like @Şivam Kuvar's example, replace :data='menu' with :data="json_encode($controllerdata)" and you're ready to use your data. According to the data structure, it can be @{{ data.data[0].title }} for example or @{{ data.title }} it depends on the ining data, my friend.

发布评论

评论列表(0)

  1. 暂无评论