Svelte keep default prop value of a child component - javascript

I have component1 that takes let text as a prop and then component2 that does almost the same thing, but I'd like to keep component1 separate for better reusability.
So I wrapped the comp1 (Child.svelte) with comp2 (Wrapper.svelte). But how do I keep the default prop value of the Child component without writing it again?
here is an example:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text = 'hello world'; //need to type the default value again
</script>
<Child text={text} />
//Child.svelte
<script lang="ts">
export let text = 'hello world';
</script>
<p>{text}</p>

Thank you #hackape and #Stephane Vanraes for your answers!
the answer from #hackape seems like the answer I was looking for, but It still throws this typescript error: Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322) when I don't provide any value to Wrapper comp. from the outside.
I should have realised this earlier, but I combined both answers and came up with this:
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string = undefined;
</script>
<Child bind:text />
also works with <Child text={text}/>
I am relatively new to Stack Overflow, should I accept my or #hackapes answer?

Use bind:prop to create a two way binding. Docs: https://svelte.dev/tutorial/component-bindings
//Wrapper.svelte
<script lang="ts">
import Child from "./Child.svelte";
export let text: string
</script>
<Child bind:text />

Related

How to use #heroicons/vue in Nuxt3?

i want to import #heroicons/vue in Nuxt 3 but my icon not appear in frontend.
my setup:
import { HomeIcon, FilmIcon, PlusIcon } from "#heroicons/vue/solid"
my html:
<template v-for="(profileItem, i) in accountSetFields" :key="i">
<ProfileItems :user="user" :item="profileItem" />
<template v-slot:icon>
<component :is="profileItem.icon"></component>
</template>
</ProfileItems>
</template>
the variable profile.Item.icon has a string value of "HomeIcon"
I have tried to pass the value directly to the child component "ProfileItem.vue" but i receive the same error message.
When i pass the value directly as string ("HomeIcon" instead of profile.Item.icon) than it works because it mentioned the attribute from import { HomeIcon, FilmIcon, PlusIcon } from "#heroicons/vue/solid
<component :is="HomeIcon"></component>
Did anyone know how to load the icons dynamically?
That one works well
<script setup>
import { HomeIcon, FilmIcon, PlusIcon } from "#heroicons/vue/24/solid"
const icons = reactive({
home: HomeIcon,
film: FilmIcon,
plus: PlusIcon,
})
</script>
<template>
<component :is="icons.home"></component>
</template>
as explained here, you need the 24 in your import (for the size).
Not sure but this may also help maybe, didn't have to use that myself: https://github.com/tailwindlabs/heroicons/issues/564
Or you can forget about worrying about various icons configuration and fallback to that one (configured once and for all): https://stackoverflow.com/a/72055404/8816585
You can also use it without <component/> and register the icon as a component. Should also work with the composition api.
<template>
<CheckCircleIcon />
</template>
<script>
import { CheckCircleIcon } from "#heroicons/vue/24/solid";
export default {
components: {
CheckCircleIcon,
}
}
</script>

Vue3 - Ref in component?

I'm making input component for my login form instead of creating input tag every time that I need it. However, I want to save the input value at #input event, thing that's I've made before (when I didn't have component) thanks to refs (by writing ref.value.value)
But now, I can't just add ref on my input because they'are component and not an html tag. How can I fix it ? :( I need their value for regExp test
there's before / after of my input
before
after
Thanks for your help
You can try this way (I used Vue3 Composition API + script setup):
Check out the playground I have set up here!
Parent component:
<template>
<Comp v-model="myData.field" />
<br />
{{ myData.field }}
</template>
<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'
const myData = ref({
field: 'something',
})
</script>
Custom input child component:
<template>
<input
type="text"
#input="$emit('update:modelValue', $event.target.value)"
:value="modelValue"
/>
</template>
<script setup>
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
Related docs:
https://vuejs.org/guide/components/props.html
https://vuejs.org/api/options-state.html#emits
Pass the ref as a prop and in the input tag put ref.
<InputComponent refProp="email" />
<input :ref="refProp" >

Why does this.renderChart not exist on CombinedVueInstance? [duplicate]

While rewriting my VueJs project in typescript, I came across a TypeScript error.
This is a part of the component that has a custom v-model.
An input field in the html has a ref called 'plate' and I want to access the value of that. The #input on that field calls the update method written below.
Typescript is complaining that value does not exist on plate.
#Prop() value: any;
update() {
this.$emit('input',
plate: this.$refs.plate.value
});
}
template:
<template>
<div>
<div class="form-group">
<label for="inputPlate" class="col-sm-2 control-label">Plate</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" #input="update">
</div>
</div>
</div>
</template>
You can do this:
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
From this issue: https://github.com/vuejs/vue-class-component/issues/94
Edit - 2021-03 (Composition API)
Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.
<template>
<div ref="root">This is a root element</div>
</template>
<script lang="ts">
import { ref, onMounted, defineComponent } from '#vue/composition-api'
export default defineComponent({
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(root.value) // <div>This is a root element</div>
})
return {
root
}
}
})
</script>
Edit - 2020-04:
The vue-property-decorator library provides #Ref which I recommend instead of my original answer.
import { Vue, Component, Ref } from 'vue-property-decorator'
import AnotherComponent from '#/path/to/another-component.vue'
#Component
export default class YourComponent extends Vue {
#Ref() readonly anotherComponent!: AnotherComponent
#Ref('aButton') readonly button!: HTMLButtonElement
}
Original Answer
None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.
class YourComponent extends Vue {
$refs!: {
vue: Vue,
element: HTMLInputElement,
vues: Vue[],
elements: HTMLInputElement[]
}
someMethod () {
this.$refs.<element>.<attribute>
}
}
son.vue
const Son = Vue.extend({
components: {},
props: {},
methods: {
help(){}
}
...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;
parent.vue
<son ref="son" />
computed: {
son(): SonRef {
return this.$refs.son as SonRef;
}
}
//use
this.son.help();
This worked for me: use
(this.$refs.<refField> as any).value or (this.$refs.['refField'] as any).value
Avoid using bracket < > to typecast because it will conflict with JSX.
Try this instead
update() {
const plateElement = this.$refs.plate as HTMLInputElement
this.$emit('input', { plate: plateElement.value });
}
as a note that I always keep remembering
Typescript is just Javascript with strong typing capability to ensure type safety. So (usually) it doesn't predict the type of X (var, param, etc) neither automatically typecasted any operation.
Also, another purpose of the typescript is to make JS code became clearer/readable, so always define the type whenever is possible.
Maybe it will be useful to someone. It looks more beautiful and remains type support.
HTML:
<input ref="inputComment" v-model="inputComment">
TS:
const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;
In case of custom component method call,
we can typecast that component name, so it's easy to refer to that method.
e.g.
(this.$refs.annotator as AnnotatorComponent).saveObjects();
where AnnotatorComponent is class based vue component as below.
#Component
export default class AnnotatorComponent extends Vue {
public saveObjects() {
// Custom code
}
}
With Vue 3 and the Options API, this is what worked for me:
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
methods: {
someAction() {
(this.$refs.foo as HTMLInputElement).value = 'abc';
},
},
});
</script>
The autocomplete doesn't bring the foo property from $refs because it's defined in the template, and apparently there's no information inferred from it.
However, once you force the casting of .foo to the HTML element type, everything works from there on, so you can access any element property (like .value, in the example above).
Make sure to wrap your exports with Vue.extend() if you are converting your existing vue project from js to ts and want to keep the old format.
Before:
<script lang="ts">
export default {
mounted() {
let element = this.$refs.graph;
...
After:
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
mounted() {
let element = this.$refs.graph;
...
I found a way to make it work but it is ugly in my opinion.
Feel free to give other/better suggestions.
update() {
this.$emit('input', {
plate: (<any>this.$refs.plate).value,
});
}
I spent a LONG time trying to find an answer to this using Vue 3, TypeScript with class components and (as it happens, although not relevant to this) TipTap. Found the answer from bestRenekton above which finally solved it, but it needed tweaking. I'm pretty sure this is TypeScript specific.
My child component has this at the start:
export default class WhealEditor extends Vue {
It includes this method (the one I want to call from the parent):
doThis(what: string) {
console.log('Called with ' + what)
}
And this right at the end:
export type EditorRef = InstanceType<typeof WhealEditor>
</script>
So this announces to any consumer of the child component that it can access it using the variable EditorRef. The parent component includes the child component in the template:
<WhealEditor ref="refEditor" />
The parent component then imports ref, and the child component and the exposed object:
import { ref } from 'vue'
import WhealEditor, { EditorRef } from './components/WhealEditor.vue'
I then have a method to get this object:
getEditor(): EditorRef {
// gets a reference to the child component
return this.$refs.refEditor as EditorRef
}
Finally, I can handle events - for example:
processButton(msg: string) {
// runs method in child component
this.getEditor().doThis(msg)
Like everything else to do with client script, it's so much harder than I expected!

Vue DOM element scrollTop is inaccessible [duplicate]

While rewriting my VueJs project in typescript, I came across a TypeScript error.
This is a part of the component that has a custom v-model.
An input field in the html has a ref called 'plate' and I want to access the value of that. The #input on that field calls the update method written below.
Typescript is complaining that value does not exist on plate.
#Prop() value: any;
update() {
this.$emit('input',
plate: this.$refs.plate.value
});
}
template:
<template>
<div>
<div class="form-group">
<label for="inputPlate" class="col-sm-2 control-label">Plate</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" #input="update">
</div>
</div>
</div>
</template>
You can do this:
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
From this issue: https://github.com/vuejs/vue-class-component/issues/94
Edit - 2021-03 (Composition API)
Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.
<template>
<div ref="root">This is a root element</div>
</template>
<script lang="ts">
import { ref, onMounted, defineComponent } from '#vue/composition-api'
export default defineComponent({
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(root.value) // <div>This is a root element</div>
})
return {
root
}
}
})
</script>
Edit - 2020-04:
The vue-property-decorator library provides #Ref which I recommend instead of my original answer.
import { Vue, Component, Ref } from 'vue-property-decorator'
import AnotherComponent from '#/path/to/another-component.vue'
#Component
export default class YourComponent extends Vue {
#Ref() readonly anotherComponent!: AnotherComponent
#Ref('aButton') readonly button!: HTMLButtonElement
}
Original Answer
None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.
class YourComponent extends Vue {
$refs!: {
vue: Vue,
element: HTMLInputElement,
vues: Vue[],
elements: HTMLInputElement[]
}
someMethod () {
this.$refs.<element>.<attribute>
}
}
son.vue
const Son = Vue.extend({
components: {},
props: {},
methods: {
help(){}
}
...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;
parent.vue
<son ref="son" />
computed: {
son(): SonRef {
return this.$refs.son as SonRef;
}
}
//use
this.son.help();
This worked for me: use
(this.$refs.<refField> as any).value or (this.$refs.['refField'] as any).value
Avoid using bracket < > to typecast because it will conflict with JSX.
Try this instead
update() {
const plateElement = this.$refs.plate as HTMLInputElement
this.$emit('input', { plate: plateElement.value });
}
as a note that I always keep remembering
Typescript is just Javascript with strong typing capability to ensure type safety. So (usually) it doesn't predict the type of X (var, param, etc) neither automatically typecasted any operation.
Also, another purpose of the typescript is to make JS code became clearer/readable, so always define the type whenever is possible.
Maybe it will be useful to someone. It looks more beautiful and remains type support.
HTML:
<input ref="inputComment" v-model="inputComment">
TS:
const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;
In case of custom component method call,
we can typecast that component name, so it's easy to refer to that method.
e.g.
(this.$refs.annotator as AnnotatorComponent).saveObjects();
where AnnotatorComponent is class based vue component as below.
#Component
export default class AnnotatorComponent extends Vue {
public saveObjects() {
// Custom code
}
}
With Vue 3 and the Options API, this is what worked for me:
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
methods: {
someAction() {
(this.$refs.foo as HTMLInputElement).value = 'abc';
},
},
});
</script>
The autocomplete doesn't bring the foo property from $refs because it's defined in the template, and apparently there's no information inferred from it.
However, once you force the casting of .foo to the HTML element type, everything works from there on, so you can access any element property (like .value, in the example above).
Make sure to wrap your exports with Vue.extend() if you are converting your existing vue project from js to ts and want to keep the old format.
Before:
<script lang="ts">
export default {
mounted() {
let element = this.$refs.graph;
...
After:
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
mounted() {
let element = this.$refs.graph;
...
I found a way to make it work but it is ugly in my opinion.
Feel free to give other/better suggestions.
update() {
this.$emit('input', {
plate: (<any>this.$refs.plate).value,
});
}
I spent a LONG time trying to find an answer to this using Vue 3, TypeScript with class components and (as it happens, although not relevant to this) TipTap. Found the answer from bestRenekton above which finally solved it, but it needed tweaking. I'm pretty sure this is TypeScript specific.
My child component has this at the start:
export default class WhealEditor extends Vue {
It includes this method (the one I want to call from the parent):
doThis(what: string) {
console.log('Called with ' + what)
}
And this right at the end:
export type EditorRef = InstanceType<typeof WhealEditor>
</script>
So this announces to any consumer of the child component that it can access it using the variable EditorRef. The parent component includes the child component in the template:
<WhealEditor ref="refEditor" />
The parent component then imports ref, and the child component and the exposed object:
import { ref } from 'vue'
import WhealEditor, { EditorRef } from './components/WhealEditor.vue'
I then have a method to get this object:
getEditor(): EditorRef {
// gets a reference to the child component
return this.$refs.refEditor as EditorRef
}
Finally, I can handle events - for example:
processButton(msg: string) {
// runs method in child component
this.getEditor().doThis(msg)
Like everything else to do with client script, it's so much harder than I expected!

How to add props to component outside of template

So let's just say that I have a HelloWorld component that I would like to import multiple times and assign some props to each one (as each instance will be doing their own thing). Usually you'll do something like this:
To keep it simple I haven't used proper syntax.
import HelloWorld from "./components/HelloWorld";
<HelloWorld v-if="which" title="0" key="1"/>
<HelloWorld v-else title="1"/>
However, I was wondering if there was a way to import them with props already assigned so something like:
import HelloWorld from "./components/HelloWorld";
import HelloWorld1 from "./components/HelloWorld";
HelloWorld.props = { title: "1" } // this doesn't work
HelloWorld1.props = { title: "2" } // this doesn't work
In order to use <component>
E.g.
<component :is="which"/>
which = "HelloWorld" || "HelloWorld1"
A component's props can only be set in the component definition object.
It looks like you're attempting to pass different prop values based on the value of which. You can do that by passing an object to v-bind:
<HelloWorld v-bind="which ? { title: '0', key: '1' } : { title: '1' }"/>

Categories