Skip to content

Instantly share code, notes, and snippets.

@kubaPod
Last active December 22, 2020 07:10
Show Gist options
  • Save kubaPod/1c3a25507fa127da2f1cd4eb26a71cf0 to your computer and use it in GitHub Desktop.
Save kubaPod/1c3a25507fa127da2f1cd4eb26a71cf0 to your computer and use it in GitHub Desktop.
A tldr; template or VSCode template

Disclaimer: I am learning

This answers a question, how to create a component that takes v-model prop can pass that prop further down.

v-model='var' is :value='var' @input='new => {var=new}' so it needs to have value prop and emit input event. But if we want to pass it down we need a localVar which can be mutated because properties can't. (unless they are objects or arrays which are passed by reference in JS but this should not be abused to not obsucre the flow)

Based on Using v-model on Nested Vue Components you should use:

<template>
    <div class='ComponentName'>
        <input v-model='localValue'> //example        
    </div>
</template>
    
<script>
    export default {
        props: {
            value: {type: Object, required: true } // or just ['value']
        },
        computed: {
            localValue: {
                get() { return this.value },
                set(v) { this.$emit('input', v) }
            }
        },
    }
</script>

<style scoped>

</style>

In VSCode navigate to Preferences > User snippets > New global snippet file and add

{
	...
	"Vue custom controller": {
		"scope": "javascript, typescript,vue",
		"prefix": "vuecc",
		"body": [
			"<template>",
			"\t<div class='${1:name}'>",
			"\t\t$0",
			"\t</div>",
			"</template>",
			"\t",
			"<script>",
			"\texport default {",
			"\t\tprops: {",
			"\t\t\tvalue: {type: ${3:Object}, required: true }",
			"\t\t},",
			"\t\tcomputed: {",
			"\t\t\t${2:local}: {",
			"\t\t\t\tget() { return this.value },",
			"\t\t\t\tset(v) { this.\\$emit('input', v) }",
			"\t\t\t}",
			"\t\t},",
			"\t}",
			"</script>",
			"",
			"<style scoped>",
			"",
			"</style>"
		],
		"description": "custom two way binding component"
	}
	
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment