VueJS Component Input Sync - vue.js

I want to create components which have input which two-way bind to the local scope of the component.
Without a component, I would create a new Vue instance and then set my data to what I need. Then using v-model, bind an input to that data and it can be manipulated from the input.
However, converting the same code to a component, I cannot for the life of me get any input in a component to bind to its data. I have tried props, :data.sync, data attributes but no matter what I have tried, the input within a component does nothing.
I have created a JSFiddle to illustrate this:
https://fiddle.jshell.net/f0pdmLhy/2/
What I would like to happen is the input in the component to two way bind to the err variable, just like the non component version underneath.
How would I accomplish this?
I basically want to create components that I can instansiate with ajax data and then populate the inputs. The inputs could then update the data and I can use a save method to send the data to the server. Can this even be done using components?

So there are a couple of things:
The external resource you were using was somehow faulty. I've used
jsfiddle default Vue instance and it works fine.
When you declare a component, you should not define the data as an object, but as a function returning an object. Read here: https://vuejs.org/guide/components.html#Component-Option-Caveats
A working example here: https://fiddle.jshell.net/by4csn1b/1/

Yes, with components, the reactivity can be accomplished just like with an instance.
One catch with components, is that data must be a function that returns an object.
Also, to maintain the two way binding, use v-model in your input.
Vue.component('ii', {
template: '<span>{{err}}</span><input type="text" v-model="err"><hr>',
data: function () {
return {
err: 123
}
}
})
Fiddle: https://fiddle.jshell.net/f0pdmLhy/25/

Related

Create component in template from data variable

I have multiple components that take same props. I want to use those components in template in such a way that I don't use multiple if-else statements in my template. I created an object in my data and paired my components with string keys. Is there a way to call those components in template with that object ? My data object looks something like this:
componentMap:{
"testComponent1":TestComponent1,
"testComponent2":TestComponent2,
},
For example, if I give "testComponent1" as key, then in template it should use TestComponent.
Use the component tag.
<component :is="componentMap['testComponent1']"></component>
See the Docs

Vue js - is that right to put all my code in watch?

I Have component A and Component B
in component A i have an API call.
when i passing info to my component b:
<B :structuresMetaData="structureTree"></B>
Inside mounted the variable structuresMetaData the length is 0
and inside the watch the length is 1.
my issue that mounted appear before the watch.
is it would be right to put all my code in watch ? if not what is the solution ?
It looks like structureTree is being changed after <B> is created/mounted.
You have two options depending on your use case:
The first option is to defer the creation of <B> until your data is loaded. This way you don't need <B> to watch for changes to the prop and the prop will be fully populated in the created/mounted hook. This is the simpler approach.
Assuming structureTree is initially an empty array:
<B
v-if="structureTree.length > 0"
:structuresMetaData="structureTree"
/>
created() {
// this.structuresMetaData is a non-empty array here
}
I usually initialize my data with null so that I can distinguish between "not loaded" and "loaded" (where "loaded" can actually be an empty array if the data I fetched from the API was empty).
The second way is using a watcher in <B> to react to changes to the prop. You will need to do this method if the bound prop might change multiple times and you need <B> to update in some way to that change.
watch: {
structuresMetaData(value) {
// React to the change, load secondary data, etc
}
}
What exactly are you doing in <B> that requires a watcher? It's best to avoid explicit watchers if you can avoid them because it usually means you are copying data around and it gets messy when you don't have a single source of truth. Use pure computed properties whenever you can if you just want to transform the data in some way.

how to solve vue short if in v-model?

I need to do a shortif in a v-model, but eslint gives the folowing problem:
[vue/valid-v-model] 'v-model' directives require the attribute value
which is valid as LHS.eslint-plugin-vue
so the code works. but its not the way it needs to work.
this is the code i have now
<v-text-field
v-show="field.type == 'String'"
v-model="_isMultiple(content_data[tabindex]) && subitem != null ? content_data[tabindex][subitem][field.name]
: content_data[tabindex][field.name]"
:label="field.name"
:counter="field.counter"
max-width="100px"
/>
So this code needs a little explanation to it.
I try to build this as an dynamic module. If I get an array back from my json response it needs to v-model the subitem. If I get an object back from the response it just needs to v-model that object.
The data (content_data[tabindex]) + field do i get from a v-for loop and other loops in my vue html
so I think its not an option to do a computed prop because
I can't get in the right data.
_isMultiple function code:
_isMultiple(content_data) {
return Array.isArray(content_data)
}
any solution for this?
Maybe you should not use v-model, but build it on your own with value binding and event listening.
v-model is only a shorthand: https://v2.vuejs.org/v2/guide/forms.html.
By implementing it on your own you can use a method to set the values and a computed property to get it.

Pass data between extended components OR call method of component

I have main component which fetch list of users in Created() method. Two next components extended of main component. In this case created method calls each time at extended components created. So i have extra call of fetch list of users. Goal is fetch users one time and pass it to extended components.
For example:
https://jsfiddle.net/apokjqxx/45/
In example we can see that Created() method of main components called two time but need one time and pass data to extended components. What's best solution for this?
Each extended component is a different object instance, that's why Created() and fetch are been executed twice.
What you need is another piece of code acting like a storage (cache) for your item's list, this piece of code should be instantiated once and shared among your components.
Vuex is probably a good option for that "piece of code"
If your math and physics component share the same data, and even have a lot in common in template, why not make them one component? This will solve your duplicated fetch issue, and you can easily rearrange your template by wrapping your current template with a v-for and use
data() {
return {
lists: [
{course: 'math', people: ['mike', 'arnold', 'tony']},
{course: 'physics', people: ['mike', 'arnold', 'tony']}
]
};
}
as your data.

Aurelia: Trigger update on one custom element when a value in another custom element changes?

I've just recently asked a question ( Refreshing i18n translated string interpolated values in Aurelia ) regarding how to refresh i18n string interpolated values when a select input field (with language ids) changes. I received a great answer, however now I realized that there was another requirement.
It's not only string interpolated values that needs to be refreshed.
In my page-specific templates I have some select fields (custom elements), which gets their option values from injecting a "service" class. That service is responsible for doing the http fetch request, and returning a promise to the select field (custom element).
Now here's the problem. When the global (language) select field from my site-wide nav-bar custom element changes, and i18n refreshing happens using the notification approach proposed in the link above. How would I then also re-fetch my different select input custom elements inside the template, but with the new language id from the language select in the nav-bar?
The only solution I know so far is to do window.location (router.navigate(sameroute) didn't trigger a refresh) and refresh the current page whenever the language select changes, however that's obviously not a great way to handle this.
I'll try to see if I can put together a plunkr, since all this may sound a little confusing.
#chrismbeckett from in https://gitter.im/Aurelia/Discuss gave me this hint:
"For those types of inter-component syncs, use the EventAggregator.
Pub a 'lang-changed' event and let any component do what it needs to
update itself"
So in nav-bar.js i did this:
let payload = { 'lngId': this.appLngId};
this.eventAggregator.publish('lang_changed', payload);
and in the custom element which were to be refreshed I put this inside the attached() function:
this.eventAggregator.subscribe('lang_changed', payload => {
alert(payload.lngId)
self.myTodosService.getMyTodos(payload.lngId);
.then(function(data){
self.myTodos = data;
})
});