gpt4 book ai didi

javascript - Vue : Child string prop wont render

转载 作者:行者123 更新时间:2023-12-01 00:24:34 25 4
gpt4 key购买 nike

嗨,我是 vue 的新手,我正在尝试了解它的单向数据绑定(bind)模型组件注册和传递属性。

在我的 index.js 中,我有我的父组件,我想立即在其中渲染单个子组件

import Vue from 'vue'
import StyledTitle from './components/StyledTitle'

new Vue({
el: '#app',
components: {
StyledTitle,
},
})

子组件是StyledTitle.js

import Vue from 'vue'
import styled from 'vue-styled-components'

const StyledTitle = styled.h1`
font-size: 1.5em;
text-align: center;
color: #ff4947;
&:hover,
&:focus {
color: #f07079;
}
`

Vue.component('styled-title', {
props: ['text'],
components: {
'styled-title': StyledTitle,
},
template: `<StyledTitle>{{ text }}</StyledTitle>`,
})

export default StyledTitle

最后我的 HTML 是我希望呈现红色的 Hi

<div id="app">
<styled-title text="Hi"></styled-title>
</div>

但是 HI 没有显示,并且 props 值未定义。从 react 中得出这一点,所以想知道为什么这不起作用,谢谢!

Ps 我的 vue devtools 截图 enter image description here

最佳答案

问题是你的StyledTitle.js文件导出正常样式 <h1>其内容使用默认插槽的组件,而不是接受 text 的自定义组件 Prop 。

如果您仍然热衷于使用基于 prop 的组件,则需要导出该组件,而不是 vue-styled-components 中的组件。 。在这种情况下,您也应该避免全局组件注册。

例如

// StyledTitle.js
import styled from 'vue-styled-components'

// create a styled title locally
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: #ff4947;
&:hover,
&:focus {
color: #f07079;
}
`

// now export your custom wrapper component
export default {
name: 'StyledTitle',
props: ['text'],
components: {
Title, // locally register your styled Title as "Title"
},
template: `<Title>{{ text }}</Title>`,
})
<小时/>

鉴于您的组件不维护任何状态,您可以将其设为 purely functional 。使用渲染函数也会有所帮助,特别是如果您的 Vue 运行时不包含模板编译器(这是大多数 Vue CLI 应用程序的默认编译器)

export default {
name: 'StyledTitle',
functional: true,
props: { text: String },
render: (h, { props }) => h(Title, props.text)
}

关于javascript - Vue : Child string prop wont render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com