繁体   English   中英

Vue:子字符串道具不会呈现

[英]Vue: Child string prop wont render

您好我是 vue 新手,正在尝试了解它的单向数据绑定模型组件注册和传递道具。

在我的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 值未定义。 从反应过来,所以想知道为什么这不起作用,谢谢!

我的vue devtools的ps截图在此处输入图像描述

问题是您的StyledTitle.js文件导出了一个普通样式的<h1>组件,该组件使用默认插槽作为其内容,而不是接受text道具的自定义组件。

如果您仍然热衷于使用基于 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>`,
})

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM