Skip to content

Instantly share code, notes, and snippets.

@LinusBorg
Last active June 24, 2019 11:04
Show Gist options
  • Save LinusBorg/0be4c97991ee3364de101aac645b335c to your computer and use it in GitHub Desktop.
Save LinusBorg/0be4c97991ee3364de101aac645b335c to your computer and use it in GitHub Desktop.
Consuming function-based plugin in object-based Vue component
<template>
<form>
<input type="text" v-model="data.name" />
<span v-if="errors.name">{errors.name.msg{</span>
<span v-else>{{capsName}}</span>
<input type="number" v-model.number="data.age" />
<span v-if="errors.age">{errors.age.msg{</span>
</form>
</template>
<script>
import useValidation from '@unknown/vue-use-validation'
import { state } from 'vue'
export default {
name: 'MyFormComponent',
setup() {
// we need to initialize state in setup instead of data()
const data = state({
name: 'Tom',
age: 13,
})
// we initialize the plugin.
// there's no need for the end user to understand any of the
// new API that is used internally (watch(), computed(), whatever)
const errors = useValidation(data)
// we return the new data and the error messages object that's essentially the result
// of a computed prop
// (but again, for the user that's an implementation detail they don't have to know.
return {
data,
errors,
}
},
mounted() {
// do your ususal stuff
},
// you can access the data from 'setup'
// and work with it like you're used to.
// similarly, you can use `methods` and
// `watch` for this data as well etc.
computed: {
capsName() {
return this.data.name.toUperCase()
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment