How to call a function from one component to another in vue.js

0

What I try to do is that when the onUpdate function is executed in component 2, the sort function is executed in component 1.

COMPONENT 1

var container = new Vue({
        el: "#main",
        data: {
            list:[{name:"John"}, 
                    {name:"Joao"}, 
                    {name:"Jean"} ],
            },
        methods:{
    sort: function(){
    alert("Hola desde otro componente")
                }
        ,
            }
        });

COMPONENT 2

  var list = document.getElementById("main");
Sortable.create(list, { 
  /* options */ 
 animation: 200, // ms, animation speed 
  ghostClass: "ghost",
  scroll: true,

    onUpdate: function (){
this.componenet1.sort();

  },

}); // That's all.

COMPLETE CODE OPEN CODE

    
asked by Jcastillovnz 05.01.2019 в 19:56
source

2 answers

1

one way is accessing the component directly

var list = document.getElementById("main");
Sortable.create(list, { 
/* options */ 
animation: 200, // ms, animation speed 
ghostClass: "ghost",
scroll: true,

onUpdate: function (){
componenet1.sort();
},

});

luck and greetings

    
answered by 05.01.2019 / 20:27
source
1

How to pass functions as props in VueJS, from a parent component to a child component.

  • App.vue

    <template>
        <div id="app">
        <child-component :onClick="sampleFunction" :fruits="sampleData"></child-component>
        </div>
    </template>
    
    <script>
    import ChildComponent from './components/ChildComponent.vue'
    
    export default {
        name: 'app',
        data(){
        return{
            sampleData: ["Apple", "Banana", "Mango", "Strawberry"]
        }
        },
        components: {
        'child-component' : ChildComponent
        },
        methods: {
        sampleFunction(fruitName){
            alert("You have selected: " + fruitName)
        }
        }
    }
    </script>
    
  • Child component

    <template>
        <div>
            <ul>
            <li v-for="fruit in fruits">
                <button type="button" @click='onClick(fruit)'> {{ fruit }}</button>
            </li>
            </ul>
        </div>
    </template>
    
    <script>
    export default {
        props: {
        onClick: Function,
        fruits: Array
        }
    }
    </script>
    
answered by 07.01.2019 в 08:00