我已经从Microsoft.AspNetCore.SpaTemplates设置了一个新的vue.js模板,并添加了一个新的控制器和路由,以了解它是如何工作的。我的问题是我添加的组件根本没有渲染。控制台显示错误:
vendor.js?v = MxNIG8b0Wz6QtAfWhyA0-4CCwZshMscBGmtIBXxKshw:13856 [Vue warn]:属性或方法“块”未在实例上定义,但在渲染期间引用。确保在数据选项中声明反应数据属性。
奇怪的是,当项目运行并且我随机更改修改模板html文件时,组件突然变得很好。
控制器:
[Route("api/[controller]")]
public class BlockController : Controller
{
[HttpGet("[action]")]
public async Task<IActionResult> Get(ulong blockNumber)
{
using (var blockRepository = new MongoRepository<Models.Block>())
{
var dbBlock = await blockRepository.GetAsync(x => x.BlockNumber == blockNumber);
return dbBlock == null ? Ok(null) : Ok(new Block()
{
BlockNumber = dbBlock.BlockNumber
});
}
}
}
public class Block
{
public ulong BlockNumber { get; set; }
}
打字稿:
import Vue from 'vue';
import { Component } from 'vue-property-decorator';
interface Block {
BlockNumber: number;
}
@Component
export default class BlockComponent extends Vue {
block: Block;
mounted() {
fetch('api/Block/Get?blockNumber=30000')
.then(response => response.json() as Promise<Block>)
.then(data => {
this.block = data;
});
}
}
模板:
<template>
<div>
<h1>Block details</h1>
<p v-if="block !== null">
Block Number: {{ block.blockNumber }}
</p>
<p v-else><em>Block not found.</em></p>
</div>
</template>
<script src="./block.ts"></script>
您需要在组件内的数据选项中初始化block
:
data () {
return {
block: null
}
},