data-binding: with文
with 文を使う
code: main.ts
const app = createApp({
setup() {
const state = reactive({ message: 'hello' })
return { state }
},
render(ctx) {
with (ctx) {
}
},
})
with文とは?
非推奨の機能
code: sample.ts
const obj = { a: 1, b: 2 }
with (obj) {
console.log(a, b) // 1, 2
}m
Vue3 でも with 文は使われているが、全てが全て with 文を使っているわけではない
SFC では template を扱う際は with 文を使わずに実装されている
今回やりたいこと
code: sample.html
<div>
<p>{{ state.message }}</p>
<button @click="changeMessage">click me</button>
</div>
↑ のようなテンプレートを
code: sample.ts
_ctx => {
with (_ctx) {
return h('div', {}, [
h('button', { onClick: changeMessage }, 'click me'), ])
}
}
↑ のような関数にコンパイルして
code: sample.ts
const setupState = setup()
render(setupState)
その関数に setupState を渡してあげる