Sending data to a non parent component in VueJs - javascript

I am trying to replicate the TODO MVC in VueJs.
(Please checkout this codepen : http://codepen.io/sankalpsingha/pen/gwymJg )
I have created a component called 'todo-list' with the following code :
Vue.component('todo-list',{
template: '#todo-list',
props: ['todo'],
data: function() {
return {
// Let us set up a isEditing Boolean so that we can know if the user
// will edit something and we need to change the state to reflect it.
isEditing: false,
}
},
methods: {
enableEditing: function() {
this.isEditing = true;
},
editTodo: function(todo) {
// todo.todo = todo.todo.trim();
this.isEditing = false;
},
removeTodo: function(todo) {
//this.todos.$remove(todo); // --> This part is not working?
}
}
});
However, I have the data defined in the app instance :
var app = new Vue({
el: '#todo-section',
data: {
newTodo: '',
todos: [
{
id: 1,
todo: 'Go to the grocery',
completed: false,
},
{
id: 2,
todo: 'See the movie',
completed: true,
},
{
id: 3,
todo: 'Jack Reacher : Tom Cruise',
completed: false,
}
]
},
methods: {
addTodo: function() {
// This will not allow any empty items to be added.
if(this.newTodo.trim() == '') {
return;
}
this.todos.push({
todo: this.newTodo.trim(),
completed: false,
});
this.newTodo = '';
}
}
});
I am not able to delete a single Todo from the list. My guess is that I have to send a emit message to the app instance and put up a listener there to delete the data from it? How do I delete the data?

When I tried to delete by clicking the x button in your codePen example, I see the error: this.$parent.todos.$remove is not a function.
I have not looked deeply into your code. But attempting to access parent component methods using this.$parent is not a good idea. Reason: a component can be used anywhere, and assuming that it will have a $parent with a particular property or method is risky.
As you suggested in your question, you need to use $emit from the child component to delete the data.
There was another similar question here few days ago, for which I created a jsFiddle: https://jsfiddle.net/mani04/4kyzkgLu/
The child component has some code like:
<button #click="$emit('delete-row')">Delete</button>
This sends out an event to parent component. Parent component can subscribe to that event using v-on as seen in that jsFiddle example.
Here is that other question for reference: Delete a Vue child component

It's preferable to use your methods (DeleteTodo, EditTodo...) in your parent.
var app = new Vue({
el: '#app',
data: {
newTodo: '',
todos: [{
id: 1,
title: 'Go to the grocery',
completed: false
}, {
id: 2,
title: 'See the movie',
completed: true
}, {
id: 3,
title: 'Jack Reacher : Tom Cruise',
completed: false
}]
},
methods: {
addTodo: function() {
this.todos.push({
todo: this.newTodo.trim(),
completed: false
});
this.newTodo = ''
},
deleteTodo: function(todo) {
this.todos = this.todos.filter(function(i) {
return i !== todo
})
}
}
});
<div id="app">
<ul>
<li v-for="todo in todos">{{ todo.title }}
<button #click.prevent="deleteTodo(todo)">
Delete
</button>
</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

Related

Trying to change data inside #click inside v-for

i have a v-for loop as my selection for dialog boxes I want to open
<v-card #click="page.model = true">
page.model is my v-model for a v-dialog
data() {
return {
dialog1: false,
dialog2: false,
pages: [
{
id: "1",
model: "dialog1",
},
{
id: "2",
model: "dialog2",
},
],
};
},
howcome #click="page.model = true" doesn't work but #click=dialog1 = true " does?
I also tried :#click="page.model = true" and #click="${page.model} = true"
Thank you in advance
So we dont see your modal HTML so I presume something like this:
<v-card v-for="page in pages" #click="changePage(page.id)">
<modal v-model="pages[0].isOpen">[CONTAIN OF PAGE 1]</modal>
<modal v-model="pages[1].isOpen">[CONTAIN OF PAGE 2]</modal>
data() {
return {
pages: [
{
id: "1",
model: "dialog1",
isOpen: false,
},
{
id: "2",
model: "dialog2",
isOpen: false,
},
],
},
methods: {
changePage(id) {
// close all other modal page
this.pages.each(el => el.isOpen = false);
// open the good one
const index = this.pages.findIndex(el => el.id == id);
this.pages[index].isOpen = true;
}
},
I have done something similar. Call a method and pass index of item. In the method you can then access the specific model via index
<v-card #click="updateDialog(index)">
updateDialog(i): {
this.pages[i].model = true
}

V-if directive not dynamically updating on variable change

I'm trying to create a button in my program that toggles on a number of other things and removes itself once it's clicked. The relevant HTML is as follows:
<div id="app">
<button #click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<list v-for="name in chosenNames" v-bind:name="name"></list>
</ul>
</div>
In this, the unordered list should be shown once the variable "showlists" is true and the button should be removed once "showlists" is true. My Vue app looks like this:
let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
showlists = true;
}
}
})
Based on this, the "showlists" variable starts as false, and the program works as intended with the button showing and the list hidden. Once the button is clicked, the function runs and showlists is then set to true (I confirmed this in my troubleshooting efforts). However, once this occurs, the DOM does not dynamically update and instead just remains as it was at the start.
Sorry if this is something really basic, I'm very new to Vue and still trying to learn :)
Any and all help would be appreciated.
You have to use the "this" keyword in your "revel" method before showlists like this.showlists = true; variable in your "Vue" instance.
For example, you can write like as follows
<div id="app">
<button #click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<list v-for="(name, index) in chosenNames" :name="name" :key="'list-'+index"></list>
</ul>
</div>
And for new "Vue" instance
let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
this.showlists = true;
}
}
})
I hope that might solve the problem :)
your code has 4 bug:
v-bind is set element's attribute, not innerHTML
showlists need change to this.showlists
showlists = true; is always set to true
list isn't valid html tag, you need li
below is right code:
<div id="app">
<button #click="reveal" v-if="!showlists">Start</button>
<ul v-if="showlists">
<li v-for="name in chosenNames" v-html="name"></li>
</ul>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
showlists: false,
chosenNames: [
{ text: "name1" },
{ text: "name2" },
{ text: "name3" },
]
},
methods: {
reveal: function() {
this.showlists = !this.showlists;
}
}
})
</script>

How to update vue-meta on route/url change?

The meta data on my website is not updating when the route changes. The route itself has a watch on it which updates the view fine, but the metaInfo() from vue-meta is not keeping up. The <script> section of my code looks like this:
<script>
export default {
name: "Product",
watch: {
'$route.params.ProductID': {
deep: true,
immediate: true,
handler() {
this.getProduct(); // calls getProduct() on route change. Can I also call metaInfo() from here somehow?
}
}
},
metaInfo() {
return {
title: this.Product.ProductTitle,
meta: [
{
name: 'description', content: this.Product.ProductTitle
}
]
}
},
computed: {
Product() {
return this.$store.getters.getProduct
}
}, mounted() {
if (this.Product == null || !this.Product.length) {
this.getProduct();
}
}, methods: {
getProduct() {
return this.$store.dispatch('loadProduct', {ProductID: this.$route.params.ProductID})
}
}
}
</script>
What is happening is that when I change my route and go from /product/123 to /product/124, the metaInfo() still shows the meta data for /product/123. If I hit refresh, then the metaInfo() updates and shows the correct data for /product/124.
I need the watch to trigger an update of metaInfo() but don't know how to do it. I can't find this information in the docs anywhere. Please help?
For reactive, use variables outside return statements.
metaInfo() {
const title = this.Product.ProductTitle;
return {
title: title,
meta: [
{
name: 'description', content: title
}
]
}
}
https://vue-meta.nuxtjs.org/guide/caveats.html#reactive-variables-in-template-functions

How to add a index in Tabulator with Vuex?

I use Tabulator with Nuxtjs
Everything works fine but when I want to add an index, I have the error
[vuex] Do not mutate vuex store state outside mutation handlers.
Here is the code
watch: {
tableData:{
handler: function (newData) {
this.tabulator.replaceData(newData);
},
deep: true,
}
},
mounted(){
this.tabulator = new Tabulator(this.$refs.table, {
index: 'p',
data: this.data,
layout: "fitData",
columns: [
{title:"Num", field:"p"},
{title:"pn", field:"pn"},
{title:"par", field:"par"},
{title:"typec", field:"typec"},
{title:"ch", field:"ch"},
{title:"ar", field:"ar"},
],
rowClick:function(e, row){
$nuxt._router.push({ path: '/C/' + row.getIndex() })
},
});
// test to upade row
this.tabulator.updateData([{p:1, pn:"test"}, {p:3, prixnom:"test"}]);
}
Thanks !
Ok, I found
it is necessary to add
created () {
this.data = JSON.parse(JSON.stringify(this.rt));
},

How to share a method between two components in Vue.js?

I have an Ag-Grid that has certain action buttons and dynamic data getting filled from a MongoDB database. I have a method on my MasterData.Vue file that refreshes the Grid. Each action button inside my grid's record perform update/delete operations. When I click on those buttons I have designed a customized pop up modal component in another Modal.Vue file. I want to call that RefreshGrid() method in Modal.Vue. I tried using props to share the data but same thing doesn't work on method.
MasterData.Vue Script
<script>
import { AgGridVue } from 'ag-grid-vue';
import { mapGetters } from 'vuex';
import gridEditButtons from '#/components/GridEditButton';
import MasterModal from '#/components/MasterModal';
export default {
name: 'masterData',
data () {
return {
addBtnClick: false,
delBtnClick: false,
editVisible: false,
selected: 'Business Area',
dropdown_tables: [
'Business Area',
'Council',
'Sub Area',
'Type',
'Work Flow Stage'
],
gridOptions: {
domLayout: 'autoHeight',
enableColumnResize: true,
rowDragManaged: true,
animateRows: true,
context: {
vm: null
}
}
};
},
components: {
'ty-master-modal': MasterModal,
'ag-grid-vue': AgGridVue,
gridEditButtons
},
methods: {
// Filter Grid Contents based on Dropdown selection
RefreshGrid: function () {
let cName;
if (this.selected === 'Business Area') {
cName = 'businessarea';
} else if (this.selected === 'Council') {
cName = 'council';
} else if (this.selected === 'Type') {
cName = 'typemaster';
} else if (this.selected === 'Work Flow Stage') {
cName = 'workflowstage';
}
let obj = {
vm: this,
collectionName: cName,
action: 'masterData/setMasterData',
mutation: 'setMasterData'
};
this.$store.dispatch(obj.action, obj);
}
};
</script>
Modal.Vue Script
<script>
import {mapGetters} from 'vuex';
export default {
name: 'MasterModal',
props: {
readOnly: Boolean,
entryData: Object,
addBtnClick: Boolean,
delBtnClick: Boolean,
editVisible: Boolean,
selectedTable: String
},
data () {
return {
fieldAlert: false,
isReadOnly: false,
dialog: false,
dialogDelete: false,
valid: false,
visible: false,
disable: false
};
},
computed: {
...mapGetters('masterData', {
entryState: 'entryState',
// entryData: 'entryData',
columns: 'columns',
selectedRowId: 'selectedRowId'
})
},
watch: {
addBtnClick: function (newValue, oldValue) {
this.setDialog(!this.dialog);
},
editVisible: function (newValue, oldValue) {
this.setVisible(!this.visible);
},
delBtnClick: function (newValue, oldValue) {
this.setDialogDelete(!this.dialogDelete);
}
},
methods: {
setDialog (bValue) {
this.dialog = bValue;
},
setDialogDelete (bValue) {
this.dialogDelete = bValue;
},
}
};
</script>
there are a couple of ways to achieve this.
One is to use the emit
in the MasterModal.vue component run this.$emit('refreshGrid') in the parent MasterData.Vue component use <ty-master-modal #refreshGrid="RefreshGrid" ...>
if you have a direct parent-child relationship, this is likely the best option
Another way is just to pass a function as a prop to the child component.
<ty-master-modal :onRefreshGrid="RefreshGrid" ...>
and add a prop onRefreshGrid to MasterModal.vue, then you can invoke the function.
Another way, using vuex, is to add a watch to MasterData.Vue and watch a variable in the vuex store ie. actionInvoker. when actionInvoker changes, the action executes. To change the value, set it to 0 and increment or toggle between, or set to random value. The advantage is that you can call this from anywhere.
The problem with this (and the previous) solution is that you have functionality tied to a view/component that shouldn't be there. I would recommend a third solution, which is to push the functionality into a vuex action, and then you can call it from anywhere. This would require though that you store the selected variable in vuex too, and if you want to have multiple instances of Modal and Master components, a singular store will prohibit that (unless you add support for multiple instances).

Categories