Vue Provide/Inject Basic Example
by Chris Ball
HTML
<div id="app">
<vue-form>
<text-input></text-input>
</vue-form>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
.help-text.danger {
color: red;
}
Vue
const VueForm = {
provide:{
errors: {
name: "The name field is required",
},
},
template: `<form>
<slot></slot>
</form>`
}
const TextInput = {
inject: ['errors'],
created(){
console.log(this.errors)
},
template: `
<div>
Name:<br>
<input type="text" name="name"><br><br>
<span v-if="this.errors.hasOwnProperty('name')"
class="help-text danger"
v-text="this.errors.name"></span>
</div>`
}
new Vue({
el: "#app",
components: {
'vue-form': VueForm,
'text-input': TextInput,
},
})