Vue 3 Composition API, Props, and v-if rendering despite false value - javascript

I have an issue I don't think I'm really understanding here. I have a child component included which passes an "active" prop in and can be set to true or false. The idea is if it's passed "true" then a part of the component shows, and if it's passed "false" it doesn't.
from what I understand, I should be able to just use the prop name and do something like:
<template>
<div v-if="active">this is the value of active: {{active}}</div>
</template>
The issue here is if I directly set v-if in the above statement to true or false, then it works as expected. If I pass it in as a prop, it always shows regardless of whether true or false.
Works (doesn't show anything):
<template>
<div v-if="false">this is the value of active: {{active}}</div>
</template>
Doesn't Work (contents in the div shows regardless of value of active):
//-File1---------------------------------------
<template>
<myComponent active=false />
</template>
//-File2---------------------------------------
<template>
<div v-if="active">this is the value of active: {{active}}</div>
</template>
<script>
export default{
props:['active']
}
</script>
Why is this? I confirmed, by displaying the value of "active" that it's passing in as false, but it's still rendering despite the value being false. Am I missing something here? I've tried playing with quotes, without quotes, passing it into a local value using ref and using that:
import { ref } from 'vue';
export default{
props:['active']
setup(props,ctx){
const active = ref(props.active);
return {
active
}
}
}
that also did not work.

It's because your prop is passed in as string from parent component (the default behavior like all other html properties). In order to pass in the prop as boolean, you need to use v-bind syntax or : for short so that false is evaluated as a javascript expression instead of string:
<template>
<myComponent v-bind:active="false" />
</template>
Or
<template>
<myComponent :active="false" />
</template>

on your export default,
props: {
active: {
type: Boolean,
default: false
}
}
on your component template,
<template>
<div v-if="active !== false"> show only when active {{ active }}</div>
</template>
when using the component, bind the active element to false
<myComponent :active="false" />

Related

Two different routes using the same child components are evaluating data differently

Using Vue3 and vue-router4, two different components share the same child components. The component templates are setup as follows:
<!-- Component A -->
<template>
<ComponentA>
<Child />
</ComponentA>
</template>
<!-- Component B -->
<template>
<ComponentB>
<Child />
</ComponentB>
</template>
<!-- Child -->
<template>
<FilterResults />
</template>
These are the configured routes:
const routes = [
{
path:'/componenta/:param',
component: ComponentA
},
{
path:'/componentb',
component: ComponentB
}
]
const router = createRouter({
history: createWebHistory(),
routes,
})
Some data is setup in the Child component:
export default {
name: 'Child'
...,
data() {
return {
filters: {
size: [
{
selected: this.$route.query.size === "1m"
}
]
}
}
}
}
The above aims to set selected to true or false depending on whether a match is found in the route. The results is then passed into FilterResults as a prop:
<!-- Component A -->
<template>
<ComponentA>
<Child />
</ComponentA>
</template>
<!-- Component B -->
<template>
<ComponentB>
<Child />
</ComponentB>
</template>
<!-- Child -->
<template>
<FilterResults :filters="filters" />
</template>
With the above, the value of selected in the filter data is evaluated and the intended result is that when the components load, the filters in the $route are set to true in the data.
The problem is, where the child components of ComponentA and ComponentB are identical:
ComponentA /componenta/xyz?size=1m does not work as intended, where matches found in the route are not set to true in the filters data.
ComponentB /componentb?size=1m does work as intended, where matches found in the route are set to true in the filters data.
I can reproduce the problem only if router-view isn't keyed, so I'm assuming that's what you have.
If there are two router-links to the same component but with different size query parameters (as shown below), and you're clicking one link and then the other, Vue reuses the existing component instance, so the component's data() is not invoked, and the query parameter is not re-evaluated.
<router-link to="/componenta/xyz?size=1m">A (size=1m)</router-link> |
<router-link to="/componenta/xyz?size=0">A (size=0)</router-link> |
To ensure a new component is created for each route change, specify a router-view key on $route.fullPath (which includes the query parameters):
<router-view :key="$route.fullPath"></router-view>
demo
In my opinion, the problem is here, your data is not recalculating on route change,
try to modify local data on route change. Try to add debugger before return statement in data, it will come only one even if change the route.

Dynamically assign directives via an object in vue

If I have a component in vue:
<template>
<component v-bind="dynamicAttrs"></component>
</template>
And I want to assign some dynamic attributes to it where v-demo is a custom directive:
data() {
return {
dynamicAttrs: {
'class': 'foo'
'v-demo': true
}
}
}
Although I can see the attbitues in the dom the custom directive is not firing in this scenario.
Is there a way I can dynamically assign directives via an object in vue?
v-bind is a directive. You can't apply a directive with another directive
It is true what Michael said but maybe you can work around it a bit:
<template>
<component :is="customComponentName" :data="dynamicAttrs"></component>
</template>
then you can create a custom component that renders based on the data you put in.
https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components
option 2:
create an custom directive and put the dynamic values in the arguments:
<template>
<component v-demo:[show]="dynamicMethod" :class="{}" />
</template>
https://v2.vuejs.org/v2/guide/custom-directive.html#Dynamic-Directive-Arguments
You could do in this manner if you genuinely want this(Just recently, I had the same thing). Although it yikes a little, but it works. If you have more directives, it becomes ugly 😉
<template>
<component class="foo" v-if="hasDemoDirective" v-demo/>
<component class="foo" v-else/>
</template>
<script>
export default {
name: 'ComponentWrapper',
props: {
hasDemoDirective: {
type: Boolean,
default: false
}
}
}
</script>

VueJS computed property using boolean prop not updating

I have a Vue (2.6.11 via Nuxt) component that gets a Boolean property from its parent and uses it to calculate additional computed properties. After the initial rendering all values are shown as expected. However, when a parent flips the value of the passed-down property, only some values change in this component. Specifically DIVs bound directly to the property and original are both fine, but flipped and stringed never change again.
Assigning the original property to a local var before any evaluation within the computed property function makes no difference in the outcome.
Changing computed properties to methods doesn't solve the issue either. It is still just the first two that update properly.
Note that the code below is stripped to a bare minimum to demonstrate the issue.
<template>
<div class="x">
<div class="y">
<div class="x">
<div>{{ flag }}</div>
</div>
<div class="x">
<div>{{ original }}</div>
</div>
<div class="x">
<div>{{ flipped }}</div>
</div>
<div class="x">
<div>{{ stringed }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "FlagBox",
props: {
"flag": {
type: Boolean
}
},
computed: {
original: function() {
return this.flag;
},
flipped: function() {
return !this.flag;
},
stringed: function() {
return this.flag ? "yes" : "no";
}
}
}
</script>
What am I missing? Thanks.
I was not able to reproduce the issue but my best guess is that the radio button you are using is emitting a string value (e.g., "false" instead of false) which is causing it to be true even when it's not.
Please check your props using the vue devtools to verify the data type being passed.
There is no other possible explanation for this, the code seems fine.

vue wrap another component, passing props and events

How can I write my component to wrap another vue component, while my wrapper component get some extra props? My wrapper template component should be:
<wrapper-component>
<v-table></v-table> <!-- pass to v-table all the props beside prop1 and prop2 -->
</wrapper-component>
and the wrapper props:
props: {
prop1: String,
prop2: String
}
Here I want to wrap a table component, and pass to the table component all the props and events that were passed to the wrapper, beside two extra props prop1 and prop2. What is the correct way of doing this in vue?
And is there a solution for events too?
Place the component you wish to wrap into the template of the wrapper component, add v-bind="$attrs" v-on="$listeners" to that component tag, then add the inner component (and, optionally, inheritAttrs: false) to the wrapper component's config object.
Vue's documentation doesn't seem to cover this in a guide or anything, but docs for $attrs, $listeners, and inheritAttrs can be found in Vue's API documentation. Also, a term that may help you when searching for this topic in the future is "Higher-Order Component" (HOC) - which is basically the same as your use of "wrapper component". (This term is how I originally found $attrs)
For example...
<!-- WrapperComponent.vue -->
<template>
<div class="wrapper-component">
<v-table v-bind="$attrs" v-on="$listeners"></v-table>
</div>
</template>
<script>
import Table from './BaseTable'
export default {
components: { 'v-table': Table },
inheritAttrs: false // optional
}
</script>
Edit: Alternatively, you may want to use dynamic components via the is attribute so you can pass in the component to be wrapped as a prop (closer to the higher-order component idea) instead of it always being the same inner component. For example:
<!-- WrapperComponent.vue -->
<template>
<div class="wrapper-component">
<component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>
</div>
</template>
<script>
export default {
inheritAttrs: false, // optional
props: ['wraps']
}
</script>
Edit 2: The part of OP's original question that I missed was passing all props EXCEPT one or two. This is handled by explicitly defining the prop on the wrapper. To quote the documentation for $attrs:
Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props
For example, example1 is recognized and extracted as a prop in the snippet below, so it doesn't get included as part of the $attrs being passed down.
Vue.component('wrapper-component', {
template: `
<div class="wrapper-component">
<component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>
</div>
`,
// NOTE: "example1" is explicitly defined on wrapper, not passed down to nested component via $attrs
props: ['wraps', 'example1']
})
Vue.component('posts', {
template: `
<div>
<div>Posts component</div>
<div v-text="example1"></div>
<div v-text="example2"></div>
<div v-text="example3"></div>
</div>
`,
props: ['example1', 'example2', 'example3'],
})
new Vue({
el: '#app',
template: `
<wrapper-component wraps="posts"
example1="example1"
example2="example2"
example3="example3"
></wrapper-component>
`,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Using props to set different text on every page in vue.js

I am using laravel + vue. I want to do title of page in navbar, so when you are in index, in navbar is text index. When you are in settings, navbar says settings etc.
I think props is good for it, but when I use that, it works not good. Look here:
blade.php of index:
#extends('layout.app')
#section('content')
<index :msg="msg"></index>
#endsection
index.vue:
props: [
'msg'
],
Now navbar:
<template>
<nav class="navbar">
<a></a>
<p>{{msg}}</p>
</nav>
</template>
<script>
export default {
props: [
],
data() {
return {
}
},
}
</script>
and layout:
<body>
<div id="app">
<navbar></navbar>
#yield('content')
</div>
</body>
How I can change that {{msg}} paragraph in navbar when we are on different pages? My code doesn't work.
[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
If you want to use a prop then you need to define it in the props object of your component. In your NavBar you are referencing to msg, but the props object in NavBar is empty. Define it and pass the prop in your layout.blade.php.
Or you could also define a computed property where you take a look at the current route and return a string fitting your business.
https://v2.vuejs.org/v2/guide/computed.html
If you want to share data between multiple components, then use a store (VUEX) as proposed :)

Categories

Resources