简体   繁体   English

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

[英]Vue: Child string prop wont render

Hi I'm new to vue and am trying to understand its one-way data bind model component registration and passing props.您好我是 vue 新手,正在尝试了解它的单向数据绑定模型组件注册和传递道具。

In my index.js I have my parent component in which I want to render a single child right now在我的index.js中,我有我的父组件,我现在想在其中渲染一个孩子

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

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

Child Component is StyledTitle.js子组件是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

Finally my HTML is which I expect to render a red Hi最后,我的 HTML 是我希望呈现红色的 Hi

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

The HI is not showing up though and the props value is undefined. HI 没有显示,并且 props 值未定义。 Coming to this from react so wondering why this isnt working, thanks!从反应过来,所以想知道为什么这不起作用,谢谢!

Ps screenshot of my vue devtools我的vue devtools的ps截图在此处输入图像描述

The issue is that your StyledTitle.js file exports a normal styled <h1> component which uses a default slot for its content instead of your custom component that accepts a text prop.问题是您的StyledTitle.js文件导出了一个普通样式的<h1>组件,该组件使用默认插槽作为其内容,而不是接受text道具的自定义组件。

If you're still keen on using a prop-based component, you need to export that instead of the one from vue-styled-components .如果您仍然热衷于使用基于 prop 的组件,则需要将其导出,而不是从vue-styled-components导出。 You should avoid global component registration in this case too.在这种情况下,您也应该避免全局组件注册。

For example例如

// 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>`,
})

Given your component doesn't maintain any state, you could make it purely functional .鉴于您的组件不维护任何状态,您可以将其设为纯功能 Using a render function will also help, especially if your Vue runtime doesn't include the template compiler (which is the default for most Vue CLI apps)使用渲染函数也会有所帮助,特别是如果您的 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