Vue Mixin - Handle Data Properties - vue.js

I am trying to use mixins for some reusable methods being used in several of my Vue SFCs.
Now, what I am worried about is how does mixins handle data properties? I find that it is too easy to make errors when using mixins (e.g. when renaming the data properties in the main component and it is being accessed in the mixin). What is the best way to handle such scenario?
// main.vue
<template>
<div>
Input Name:
<input v-model="mainComponentValue" placeholder="edit me">
<br/><br/>
{{ welcomeMessage }} <br/>
Member ID: {{ getMemberIdNum() }}
<br/><br/>
{{ checkMemberOftheMonth() }}
<br/><br/><br/>
{{ someMainComponentMethod() }}
</div>
</template>
<script>
import mixin from ‘./mixin.js’
export default {
mixins: [mixin],
data () {
return {
title: 'Component',
mainComponentValue: 'John'
}
},
methods: {
someMainComponentMethod () {
return 'This is a computed property from the mixin: ' + this.memberName
}
}
}
</script>
Then on my mixin:
// mixin.js
export default {
data () {
return {
mixinSampleValue: 'Hello there'
}
},
computed: {
welcomeMessage () {
return this.mixinSampleValue + ', ' + this.mainComponentValue.toUpperCase() + '!'
},
memberName () {
return this.mainComponentValue.toLowerCase()
}
},
methods: {
getMemberIdNum () {
switch (this.memberName) {
case 'john':
return '0001'
case 'roger':
return '0002'
default:
return '0003'
}
},
checkMemberOftheMonth () {
// use main component's data
if (this.memberName === 'john') {
return 'Congratulations, you are our member of the month!'
}
}
}
}
As you can see, main.vue data properties are used in the mixin and vice versa (and computed properties and methods).. So I worry that if I change the data property name (let's say mainComponentValue to name) at main.vue or any other vue component that uses the mixin, then it will mess my mixin up. And vice versa when I change a computed property from the mixin, then main.vue will be messed up.
Any way I can add certain checkings for cases like this?
For reference, here is a sample CodePen:
https://codepen.io/keechan/pen/eYBRQGM
Thanks!

We do not use mixins anymore (almost). We had the same issues in our dev team, that it is not obvious inside a component what the mixin provides.
Instead we use full or renderless components with scoped slots or we simply import some functions from a lib directory that we want to share across several vue components.
Another alternative is the Composition API, see also: https://css-tricks.com/how-the-vue-composition-api-replaces-vue-mixins/

Related

Pass Vue js search filter functionality through single file components with EventBus

I have the following components:
/components/SearchBlogs.vue Search component to filter on blog.title and blog.description.
/components/BlogList.vue Here I list all the Blog items.
SearchBlogs.vue
<template>
<div>
<input type="text" v-model="search" #change="emitSearchValue" placeholder="search blog">
</div>
</template>
<script>
import { EventBus } from '../event-bus.js'
export default {
name: 'SearchBlogs',
data: () => {
return {
search: ''
}
},
methods: {
emitSearchValue() {
EventBus.$emit('search-value', 'this.search')
}
}
}
</script>
BlogList.vue
<template>
<div>
<div v-for="blog in filteredBlogs" :key="blog">
<BlogListItem :blog="blog" />
</div>
</div>
</template>
<script>
import BlogListItem from './BlogListItem'
import { EventBus } from '../event-bus.js'
export default {
name: 'BlogList',
components: {
BlogListItem,
},
data: () => {
return {
blogs: [],
searchvalue: ''
}
},
computed: {
filteredBlogs() {
return this.blogs.filter(blog =>
blog.name.toLowerCase().includes(
this.searchvalue.toLowerCase()
)
)
}
},
created() {
fetch('http://localhost:3000/blogs')
.then(response => {
return response.json();
})
.then(data => {
this.blogs = data;
}),
EventBus.$on('search-value', (search) => {
this.searchvalue = value;
})
}
}
</script>
In another page component Blogs I register both components:
<template>
<div>
<h1>Blog</h1>
<TheSidebar>
<SearchBlogs />
</TheSidebar>
<BlogList/>
</div>
</template>
Can anybody see what's missing here? I want, as soon as the user types something in the search input (from the SearchBlogs.vue component), it start filtering and updating the list.
Look at my solution condesandbox
Here is an explanation:
You don't need to use EventBus. You can communicate with Search Component by v-model, using prop value and emiting updated value from the Input.
Then your Main (List) Component is responsible for all the logic.
It keeps the state of a Search
It keeps the items and filtered Items
Thanks to that your Search Component is very clear and has no data, that means it has very little responsibility.
Please ask questions if I can add something to help you understand 😉
UPDATE:
EventBus is a great addition in some cases. Your case is simple enough, there is no need to add it. Right now your architecture is "over engineered".
When you have added listener on EventBus, on created:hookyou should always remove it while Component is being destroyed. Otherwise you can encounter a trouble with double calling function etc. This is very hard to debug, tryst me I'he been there 😉
Going with my suggestion gives you comfort of "no-need-to-remember-about-this" because Vue is doing it for you.
Hope that help.
Couple of issues but essentially the computed prop filteredData will look like:
computed: {
filteredData() {
return this.experiences.filter(
el => el.category.indexOf(this.search) > -1
);
}
}
Also, used quotes around 'this.search' when passing its value back which made it a string.
Fixed sandbox
https://codesandbox.io/s/reverent-lamarr-is8jz

Data property no longer reactive after doing simple re-assignment?

I have a data property called current_room where initially it has an empty object {}.
I have a component that will receive current_room as a "prop".
In the parent component, in the mounted() hook, re-assignment takes place: this.current_room = new_room
In the child component, the current_room prop appears to be... an empty object. In the parent component, it's not an empty object, it has the data I expect to see.
What would be the proper way to make this work? It seems as though simple re-assignment doesn't work in this case, that once I define a property on the data object... and that property is an object... I have to add/remove properties to the object, rather than just wholesale re-assigning a new object to that data property.
I guess it's just a simple mistake somewhere in your code. Because following to your question - it should work, furthermore I created a simple example where I defined components and functionality as you've described - and it works. I will provide async example to make you sure for 100 percents.
Here is the working example:
App.vue
<template>
<div id="app">
<CurrentRoom :room="current_room" />
</div>
</template>
<script>
import CurrentRoom from './components/CurrentRoom.vue'
export default {
name: "App",
components: {
CurrentRoom
},
data () {
return {
current_room: {}
}
},
mounted () {
setTimeout(() => {
this.current_room = {
door: true,
windowsCount: 2,
wallColor: 'white',
members: [
{
name: 'Heisenberg',
age: 46
},
{
name: 'Pinkman',
age: 26
}
]
}
}, 2000)
}
};
</script>
CurrentRoom.vue
<template>
<div>
Current room is: <br>
<pre>{{ room }}</pre>
</div>
</template>
<script>
export default {
name: 'CurrentRoom',
props: {
room: {
type: Object,
default: () => {}
}
}
}
</script>
Codesandbox demo:
https://codesandbox.io/s/epic-banach-clyz4
And for the end, following to your question:
... What would be the proper way to make this work? ...
The answer is - 'Please, compare your code with provided example'

Vue best practice for calling a method in a child component

I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.
To make this simple I have created a really simple version of what I would like to achieve.
I have a parent Vue, parent.vue. It has a button:
<template>
<div>
<button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
</div>
</template>
In the child Vue, child.vue I have a method with a function:
methods: {
sayHello() {
alert('hello');
}
}
I would like to call the sayHello() function when I click the button in the parent.
I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.
What would be the simplest way to just execute the function in my method?
Apologies, this does seem extremely simple, but I have really tried to do some research.
Thanks!
One easy way is to do this:
<!-- parent.vue -->
<template>
<button #click="$refs.myChild.sayHello()">Click me</button>
<child-component ref="myChild" />
</template>
Simply create a ref for the child component, and you will be able to call the methods, and access all the data it has.
You can create a ref and access the methods, but this is not recommended. You shouldn't rely on the internal structure of a component. The reason for this is that you'll tightly couple your components and one of the main reasons to create components is to loosely couple them.
You should rely on the contract (interface in some frameworks/languages) to achieve this. The contract in Vue relies on the fact that parents communicate with children via props and children communicate with parents via events.
There are also at least 2 other methods to communicate when you want to communicate between components that aren't parent/child:
the event bus
vuex
I'll describe now how to use a prop:
Define it on your child component
props: ['testProp'],
methods: {
sayHello() {
alert('hello');
}
}
Define a trigger data on the parent component
data () {
return {
trigger: 0
}
}
Use the prop on the parent component
<template>
<div>
<childComponent :testProp="trigger"/>
</div>
</template>
Watch testProp in the child component and call sayHello
watch: {
testProp: function(newVal, oldVal) {
this.sayHello()
}
}
Update trigger from the parent component. Make sure that you always change the value of trigger, otherwise the watch won't fire. One way of doing this is to increment trigger, or toggle it from a truthy value to a falsy one (this.trigger = !this.trigger)
I don't like the look of using props as triggers, but using ref also seems as an anti-pattern and is generally not recommended.
Another approach might be: You can use events to expose an interface of methods to call on the child component this way you get the best of both worlds while keeping your code somehow clean. Just emit them at the mounting stage and use them when pleased. I stored it in the $options part in the below code, but you can do as pleased.
Child component
<template>
<div>
<p>I was called {{ count }} times.</p>
</div>
</template>
<script>
export default {
mounted() {
// Emits on mount
this.emitInterface();
},
data() {
return {
count: 0
}
},
methods: {
addCount() {
this.count++;
},
notCallable() {
this.count--;
},
/**
* Emitting an interface with callable methods from outside
*/
emitInterface() {
this.$emit("interface", {
addCount: () => this.addCount()
});
}
}
}
</script>
Parent component
<template>
<div>
<button v-on:click="addCount">Add count to child</button>
<child-component #interface="getChildInterface"></child-component>
</div>
</template>
<script>
export default {
// Add a default
childInterface: {
addCount: () => {}
},
methods: {
// Setting the interface when emitted from child
getChildInterface(childInterface) {
this.$options.childInterface = childInterface;
},
// Add count through the interface
addCount() {
this.$options.childInterface.addCount();
}
}
}
</script>
With vue 3 composition api you can do it like this:
Parent.vue
<script setup lang="ts">
const childRef = ref()
const callSayHello = () => {
childRef.value.sayHello()
}
</script>
<template>
<child ref="childRef"></child>
</template>
<style scoped></style>
Child.vue
<script setup lang="ts">
const sayHello = () => {
console.log('Hello')
}
defineExpose({ sayHello })
</script>
<template></template>
<style scoped></style>
I am not sure is this the best way. But I can explain what I can do...
Codesandbox Demo : https://codesandbox.io/s/q4xn40935w
From parent component, send a prop data lets say msg. Have a button at parent whenever click the button toggle msg true/false
<template>
<div class="parent">
Button from Parent :
<button #click="msg = !msg">Say Hello</button><br/>
<child :msg="msg"/>
</div>
</template>
<script>
import child from "#/components/child";
export default {
name: "parent",
components: { child },
data: () => ({
msg: false
})
};
</script>
In child component watch prop data msg. Whenever msg changes trigger a method.
<template>
<div class="child">I am Child Component</div>
</template>
<script>
export default {
name: "child",
props: ["msg"],
watch: {
msg() {
this.sayHello();
}
},
methods: {
sayHello() {
alert("hello");
}
}
};
</script>
This is an alternate take on Jonas M's excellent answer. Return the interface with a promise, no need for events. You will need a Deferred class.
IMO Vue is deficient in making calling child methods difficult. Refs aren't always a good option - in my case I need to call a method in one of a thousand grandchildren.
Parent
<child :getInterface="getInterface" />
...
export default {
setup(props) {
init();
}
async function init() {
...
state.getInterface = new Deferred();
state.childInterface = await state.getInterface.promise;
state.childInterface.doThing();
}
}
Child
export default {
props: {
getInterface: Deferred,
},
setup(props) {
watch(() => props.getInterface, () => {
if(!props.getInterface) return;
props.getInterface.resolve({
doThing: () => {},
doThing2: () => {},
});
});
}
}

VueJS functional components (SFC): how to encapsulate code?

I wrote a simple template-substitution component in VueJS as a single-file component. It doesn't have many features: just one prop, and I also made a computed property to encapsulate some tricky transformations that are done to that prop before it can be used in the template. It looks something like the following:
<template>
...some-html-here...
<a :href="myHref">...</a>
...
</template>
<script>
export default {
name: 'MyComponent',
props: {
href: { type: String, required: true },
},
computed: {
myHref() {
let result = this.href;
// several lines of complicated logic making substitutions and stuff
// ...
return result;
}
}
};
</script>
Now I think this should really be a functional component, as it has no state, no data, no reactivity, and so lunking around a whole instance is wasteful.
I can make this functional just by adding the 'functional' attribute to my <template>. In a functional component, of course, there are no such things as computed properties or methods or whatever. So my question is: where can I put my several lines of complicated logic? I don't want to have to embed this directly into my template, especially as it is used in multiple places. So where can I put code to transform my input props and make them ready to use in my template?
Great question.I was trying to find the same answer and i ended up with the following which i don't know if it is a good way to do though.
The "html" part:
<template functional>
<div>
<button #click="props.methods.firstMethod">Console Something</button>
<button #click="props.methods.secondMethod">Alert Something</button>
</div>
</template>
The "js" part:
<script>
export default {
props: {
methods: {
type: Object,
default() {
return {
firstMethod() {
console.log('You clicked me')
},
secondMethod() {
alert('You clicked me')
}
}
}
}
}
}
</script>
See it in action here
Make sure to read about functional components at docs
NOTE: Be aware using this approach since functional components are stateless (no reactive data) and instanceless (no this context).

VueJs - Passing data to subRoutes component with vue-router

I don't understand how to pass data loaded by a 'route Component' to a 'subRoute Component'..
(I'm using Vue.js with Vue-router)
My router looks like that:
router.map({
'/a': {
component: A,
subRoutes: {
'/b': {
component: B
},
'/c': {
component: C
}
}
}
});
I just want to share data loaded by component A with component B and C.
Thanks in advance !
You have two simple options.
The ugly
Use the $parent option from the subroute components. That give you access to the parent instance, it's not the recommended way, but it's effective
// from the child component
this.$parent.someData
The good
Use props. Props give you the chance to pass any data from the parent to a child. It's better, because prevents error (you pass data not an instance) and you pass only what you need, even if it isn't part of the parent data.
// parent component
<template>
<child :childsdata="parentdata"></child>
</template
<script>
export default {
data: function () {
return {
parentdata: 'Hello!'
}
}
}
</script>
// child component
<template>
{{ childsdata }} <!-- prints "Hello!" -->
</template>
<script>
export default {
props: {
childsdata: {
type: String
}
}
}
</script>