Skip to content

Commit

Permalink
feature: play around with provide inject
Browse files Browse the repository at this point in the history
  • Loading branch information
bencodezen committed Aug 10, 2020
1 parent 32d53d8 commit 378ac81
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
17 changes: 15 additions & 2 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<img alt="Vue logo" src="./assets/logo.png" />
<p>{{ book }}</p>
<HelloWorld msg="Welcome to Your Vue.js App" />
</div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import { useBook } from './features/useBook'
import { provide, readonly } from 'vue'
export default {
name: 'App',
components: {
HelloWorld
},
setup() {
const { book, changeBookName } = useBook()
provide('book', readonly(book))
provide('changeBookName', changeBookName)
return {
book
}
}
}
</script>
Expand Down
13 changes: 12 additions & 1 deletion src/components/HelloWorld.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,26 @@
<p>{{ width }}</p>
<button @click="reportWidth">Show Width in Alert Box</button>
<p>{{ widthDoubled }}</p>
<h2>Inject</h2>
<p>Book: {{ book }}</p>
<button @click="changeName('New Book')">Change Book Name</button>
</div>
</template>

<script>
import { useWindowWidth } from '../features/useWidth'
import { inject } from 'vue'
export default {
setup() {
const { width } = useWindowWidth()
const book = inject('book')
const changeBookName = inject('changeBookName')
return {
width
width,
book,
changeBookName
}
},
computed: {
Expand All @@ -23,6 +31,9 @@ export default {
}
},
methods: {
changeName(title) {
this.book.title = title
},
reportWidth() {
alert(this.width)
}
Expand Down
20 changes: 20 additions & 0 deletions src/features/useBook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { reactive } from 'vue'

// in provider
export const useBook = () => {
const book = reactive({
title: 'Vue 3 Guide',
author: 'Vue Team'
})

function changeBookName(customName, $event) {
console.log(customName)
console.log($event)
book.title = customName || 'Vue 3 Advanced Guide'
}

return {
book,
changeBookName
}
}

0 comments on commit 378ac81

Please sign in to comment.