refactor(template-ref): improve template ref handling

close #836, close #839
This commit is contained in:
Evan You
2020-03-16 12:40:58 -04:00
parent 8a58dce603
commit 9ad65b1653
6 changed files with 55 additions and 114 deletions

View File

@@ -1,40 +0,0 @@
import { NodeTransform } from '../transform'
import {
NodeTypes,
ElementTypes,
createSimpleExpression,
createCompoundExpression
} from '../ast'
import { findProp } from '../utils'
// Convert ref="foo" to `:ref="[_ctx, 'foo']"` so that the ref contains the
// correct owner instance even inside slots.
export const transformRef: NodeTransform = node => {
if (
!(
node.type === NodeTypes.ELEMENT &&
(node.tagType === ElementTypes.ELEMENT ||
node.tagType === ElementTypes.COMPONENT)
)
) {
return
}
const ref = findProp(node, 'ref')
if (!ref) return
const refKey =
ref.type === NodeTypes.ATTRIBUTE
? ref.value
? createSimpleExpression(ref.value.content, true, ref.value.loc)
: null
: ref.exp
if (refKey) {
node.props[node.props.indexOf(ref)] = {
type: NodeTypes.DIRECTIVE,
name: `bind`,
arg: createSimpleExpression(`ref`, true, ref.loc),
exp: createCompoundExpression([`[_ctx, `, refKey, `]`]),
modifiers: [],
loc: ref.loc
}
}
}