我可能已经找到了解决方案,我将在此处发布以供参考。它目前有效,但我不能说它以后不会给我带来麻烦,如果你找到更好的方法,我很乐意看看。
像往常一样创建了一些刀片组件之后
php artisan make:component MyComponent1
php artisan make:component MyComponent2
php artisan make:component MyComponent3
在声明了所有需要的属性和方法后,您可以以常规方式将组件包含在视图中
<html>
<head></head>
<body>
@if($somethingHappens)
<x-my-component1 a="" b="" :c="$c" class="" />
@elseif ($somethingElseHappens)
<x-my-component2 a="" b="" :c="$c" class="" />
@else
<x-my-component3 a="" b="" :c="$c" class="" />
@endif
</body>
</html>
或者,如果您希望更灵活地决定在运行时应该使用哪个组件并在视图之外的其他地方生成组件标签,我已经找到了这个解决方案
//some code.....
return('myview')->with([
'type' => 'component',
'component' => '<x-my-component3 a="" b="" :c="$vars[\'c\']" class="" />',
'vars' => [ 'c' => 'somevalue' ]
]);
#################
//myview.blade.php
<html>
<head></head
<body>
@php
if($type == 'component')
echo compileStringComponent(
$component,
$__env,
$vars
);
@endphp
</body>
</html>
################
//file containing the function
use Illuminate\View\Factory as ViewFactory;
//This function takes the whole tagged component as string and returns the corresponding html
function compileStringComponent(string $component, ViewFactory $__env, $vars = null )
{
$compiled = Blade::compileString($component);
ob_start();
try {
eval('?>'.$compiled);
} catch (\Exception $e){
ob_get_clean();
throw( $e);
}
$content = ob_get_clean();
return $content;
}
几点说明:
1) Blade::compileString 返回一个编译后的字符串以进行评估,并且在代码内部有一些对 $__env 变量的引用,该变量是 Illuminate\View\Factory 的一个实例,并且已经存在于视图中。这意味着如果在视图之外调用函数,则必须将 $__env 变量传递给调用者
2) 如果数据通过 :attributes 传递给组件,则需要 $vars 数组,原因与上述相同,因为这些变量不会存在于调用者内部,必须传递给它
3) ob_start() 和 ob_get_clean() 用于避免在出现任何错误时向用户发送不完整的视图。
希望对大家有所帮助